-2

My code is like this :

var createdDate = '2013-01-21 01:23:44';
createdDate = new Date(createdDate);
date = createdDate.toLocaleDateString();
time = createdDate.toLocaleTimeString().replace(/(.*)\D\d+/, '$1');
console.log(date+' '+time);

The result : 1/21/2013 1:23 AM

I want the result : 2013-01-21 1:23 AM

Any solution to solve my problem?

moses toh
  • 2,860
  • 14
  • 55
  • 125
  • 2
    Does this not help? http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – evolutionxbox Jul 13 '16 at 16:12
  • 1
    I'd suggest using a library for this, such as [Date.js](http://www.datejs.com/), as date formatting in JS is a huge pain. You have to write far too much code to do it. – Rory McCrossan Jul 13 '16 at 16:15
  • You can also use a [date formating library](http://jacwright.com/projects/javascript/date_format/), for example `createdDate.format.format('Y-m-d g:i A')` will output `"2016-07-13 5:14 PM"` – evolutionxbox Jul 13 '16 at 16:19

2 Answers2

5

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"
jszpila
  • 614
  • 8
  • 23
  • 1
    Thank you, I was using moment for a while now and didn't know it was capable of this. A small add: you can load the time string directly into the call like `moment(time_string).format("DD.MM.YYYY HH:mm")` – Peon Jun 28 '17 at 14:15
1

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.

Vadim
  • 1,650
  • 2
  • 17
  • 31