Some basic and useful functions in JavaScript to manipulate date, string and so on
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*Date functions*/ | |
| /** | |
| * Returns the number of the current week | |
| * @returns {number} – Number of the current week | |
| */ | |
| Date.prototype.getWeek = function() | |
| { | |
| var date = new Date(this.getTime()); | |
| date.setHours(0, 0, 0, 0); | |
| // Thursday in current week decides the year. | |
| date.setDate(date.getDate() + 3 – (date.getDay() + 6) % 7); | |
| // January 4 is always in week 1. | |
| var week1 = new Date(date.getFullYear(), 0, 4); | |
| // Adjust to Thursday in week 1 and count number of weeks from date to week1. | |
| return 1 + Math.round(((date.getTime() – week1.getTime()) / 86400000 – 3 + (week1.getDay() + 6) % 7) / 7); | |
| } | |
| /** | |
| * Determines whether or not a date have a valid format | |
| * @param {date} date – Date to check | |
| * @returns {boolean} – Determine whether or not the date checked is valid | |
| */ | |
| function isValidDate(date) | |
| { | |
| var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date); | |
| if (matches == null) return false; | |
| var d = matches[1]; | |
| var m = matches[2]-1; | |
| var y = matches[3]; | |
| var composedDate = new Date(y, m, d); | |
| return composedDate.getDate() == d && | |
| composedDate.getMonth() == m && | |
| composedDate.getFullYear() == y; | |
| } | |
| /** | |
| * Adds months to a date | |
| * @param {*} date – Date to increment | |
| * @param {*} months – Number of months to add to the initial date entered | |
| */ | |
| function addMonths(date, months) | |
| { | |
| date.setMonth(date.getMonth() + months); | |
| return date.format("dd/MM/yyyy"); | |
| } | |
| /*String functions*/ | |
| /** | |
| * Remove accented characters | |
| * @param {*} string – Text to format | |
| */ | |
| removeAccentedCharacter = function (value) { | |
| return !value ? | |
| '' : | |
| typeof value === 'string' ? | |
| value | |
| .replace(/\n/g, ' ') | |
| .replace(/á/g, 'a') | |
| .replace(/à/g, 'a') | |
| .replace(/é/g, 'e') | |
| .replace(/í/g, 'i') | |
| .replace(/ó/g, 'o') | |
| .replace(/ú/g, 'u') | |
| .replace(/ê/g, 'e') | |
| .replace(/î/g, 'i') | |
| .replace(/ô/g, 'o') | |
| .replace(/è/g, 'e') | |
| .replace(/é/g, 'e') | |
| .replace(/ï/g, 'i') | |
| .replace(/ü/g, 'u') | |
| .replace(/ç/g, 'c') : | |
| value; | |
| }; |
