JavaScript methods for formatting dates and times and examples of custom formatting functions

  • 2020-03-30 02:34:25
  • OfStack

Many times, we can use the built-in methods of Date object in JavaScript to format, such as:

var d = new Date();
console.log(d); //Output: Mon Nov 04 2013 21:50:33 GMT + 0800 (China standard time)
console.log(d.toDateString()); //Date string, output: Mon Nov 04 2013
console.log(d.toGMTString()); //GMT, output: Mon, 04 Nov 2013 14:03:05 GMT
console.log(d.toISOString()); //International standards organization (ISO) format, output: 2013-11-04 t14:03:05.420z
console.log(d.toJSON()); //Output: the 2013-11-04 T14:03:05. 420 z
console.log(d.toLocaleDateString()); //Convert to local date format, depending on the environment, output: November 4, 2013
console.log(d.toLocaleString()); //Convert to local date and time format, depending on the environment, output: November 4, 2013 10:03:05 PM
console.log(d.toLocaleTimeString()); //Convert to local time format, depending on the environment, output: 10:03:05 p.m
console.log(d.toString()); //Convert to string, output: Mon Nov 04 2013 22:03:05 GMT + 0800 (Chinese standard time)
console.log(d.toTimeString()); //Convert to time string, output: 22:03:05 GMT + 0800 (Chinese standard time)
console.log(d.toUTCString()); //Convert to world time, output: Mon, 04 Nov 2013 14:03:05 GMT

If the above method does not meet our requirements, we can also customize the function to format the time, such as:

Date.prototype.format = function(format) {
       var date = {
              "M+": this.getMonth() + 1,
              "d+": this.getDate(),
              "h+": this.getHours(),
              "m+": this.getMinutes(),
              "s+": this.getSeconds(),
              "q+": Math.floor((this.getMonth() + 3) / 3),
              "S+": this.getMilliseconds()
       };
       if (/(y+)/i.test(format)) {
              format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
       }
       for (var k in date) {
              if (new RegExp("(" + k + ")").test(format)) {
                     format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
              }
       }
       return format;
}
var d = new Date().format('yyyy-MM-dd');
console.log(d); // 2013-11-04

 


Related articles: