Skip to content Skip to sidebar Skip to footer

How To Change Datetime Format In Javascript?

My code is like this : var createdDate = '2013-01-21 01:23:44'; createdDate = new Date(createdDate); date = createdDate.toLocaleDateString(); time = createdDate.toLocaleTimeString(

Solution 1:

There are, of course, vanilla solutions but working with date/time in JS is generally a pain. If you're going to be working with date/time in any serious capacity I would highly recommend using Moment.js's format method for its robustness and flexibility, and it should be able to do what you want.

Examples from the docs:

moment().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA");                       // "Sun, 3PM"
moment('gibberish').format('YYYY MM DD');         // "Invalid date"

Solution 2:

You could extend the Number class to allow for zero padding (to display single-digit days and months with zeroes in the front):

Number.prototype.pad = function(size) {
  var s = String(this);
  while (s.length < (size || 2)) {s = "0" + s;}
  return s;
}

The pad function takes an optional size parameter which dictates the total length of the number string with the default value of 2.

You could then update your existing code to split the date into three components (using the pad function when printing the result):

var createdDate = new Date('2013-01-21 01:23:44');
var date = createdDate.toLocaleDateString();

var day = createdDate.getDate();
var month = createdDate.getMonth() + 1; //months are zero based
var year = createdDate.getFullYear();

var time = createdDate.toLocaleTimeString().replace(/(.*)\D\d+/, '$1');

console.log(year + '-' + month.pad() + '-' + day.pad() + ' ' + time);

If you are looking for more elegant or less verbose solutions, you will need to use external libraries.


Post a Comment for "How To Change Datetime Format In Javascript?"