Created
February 2, 2016 18:11
-
-
Save mityukov/9bab25077a57060848ee to your computer and use it in GitHub Desktop.
JavaScript: Date() helpers + paddingLeft()
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
/** | |
* Pads string or number with symbols | |
* @param {string} paddingValue Padding string. E.g., "0000" | |
* @return {string} E.g., "0032" | |
*/ | |
String.prototype.paddingLeft = function (paddingValue) | |
{ | |
return String(paddingValue + this).slice(-paddingValue.length); | |
}; | |
/** | |
* Formats date to "DD.MM.YY" format | |
* @param {string} separator Optional separator. Default value: "." | |
* @return {string} Formatted date | |
*/ | |
Date.prototype.ddmmyy = function(separator) | |
{ | |
if (!separator) { separator = '.'; } | |
var dateComponents = [ | |
this.getDay().toString().paddingLeft("00"), | |
(this.getMonth()+1).toString().paddingLeft("00"), | |
year = this.getFullYear().toString().substr(-2) | |
]; | |
return dateComponents.join(separator); | |
}; | |
/** | |
* Formats date to "DD.MM.YYYY" format | |
* @param {string} separator Optional separator. Default value: "." | |
* @return {string} Formatted date | |
*/ | |
Date.prototype.ddmmyyyy = function(separator) | |
{ | |
if (!separator) { separator = '.'; } | |
var dateComponents = [ | |
this.getDay().toString().paddingLeft("00"), | |
(this.getMonth()+1).toString().paddingLeft("00"), | |
year = this.getFullYear().toString() | |
]; | |
return dateComponents.join(separator); | |
}; | |
/** | |
* Formats date to "YYYY-MM-DD" format | |
* @param {string} separator Optional separator. Default value: "-" | |
* @return {string} Formatted date | |
*/ | |
Date.prototype.yyyymmdd = function(separator) | |
{ | |
if (!separator) { separator = '-'; } | |
var dateComponents = [ | |
year = this.getFullYear().toString(), | |
(this.getMonth()+1).toString().paddingLeft("00"), | |
this.getDay().toString().paddingLeft("00") | |
]; | |
return dateComponents.join(separator); | |
}; | |
/** | |
* Returns Date object which is numDays days ahead of original date | |
* @param {int} numDays Optional number of days. Default value: 1 | |
* @return {Date} | |
*/ | |
Date.prototype.nextDay = function(numDays) | |
{ | |
if (!numDays) { numDays = 1; } | |
return new Date(this.getTime() + numDays * 24 * 60 * 60 * 1000); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment