Skip to content

Instantly share code, notes, and snippets.

@cstipkovic
Last active July 31, 2017 03:02
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save cstipkovic/3983879 to your computer and use it in GitHub Desktop.
Save cstipkovic/3983879 to your computer and use it in GitHub Desktop.
A simple format Date function using Javascript prototype
/*
Based on Rick Strahl code
http://www.west-wind.com/weblog/posts/2008/Mar/18/A-simple-formatDate-function-for-JavaScript
Contributors:
Clauber Stipkovic - @clauberhalic
Mário Rinaldi - @MarioRinaldi
*/
Date.prototype.formatDate = function (format) {
var date = this,
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
if (!format) {
format = "MM/dd/yyyy";
}
format = format.replace("MM", month.toString().replace(/^(\d)$/, '0$1'));
if (format.indexOf("yyyy") > -1) {
format = format.replace("yyyy", year.toString());
} else if (format.indexOf("yy") > -1) {
format = format.replace("yy", year.toString().substr(2, 2));
}
format = format.replace("dd", day.toString().replace(/^(\d)$/, '0$1'));
if (format.indexOf("t") > -1) {
if (hours > 11) {
format = format.replace("t", "pm");
} else {
format = format.replace("t", "am");
}
}
if (format.indexOf("HH") > -1) {
format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1'));
}
if (format.indexOf("hh") > -1) {
if (hours > 12) {
hours -= 12;
}
if (hours === 0) {
hours = 12;
}
format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1'));
}
if (format.indexOf("mm") > -1) {
format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1'));
}
if (format.indexOf("ss") > -1) {
format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1'));
}
return format;
};
@jhlee8804
Copy link

jhlee8804 commented Oct 18, 2016

support utc date formatting

Date.prototype.format = function (format, utc) {
      var date = this,
        day = utc ? date.getUTCDate() : date.getDate(),
        month = (utc ? date.getUTCMonth() : date.getMonth()) + 1,
        year = utc ? date.getUTCFullYear() : date.getFullYear(),
        hours = utc ? date.getUTCHours() : date.getHours(),
        minutes = utc ? date.getUTCMinutes() : date.getMinutes(),
        seconds = utc ? date.getUTCSeconds() : date.getSeconds();

      ....
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment