0

I am trying to convert a string format of date into a date object in JavaScript. I am getting different kinds of date formats like "dd/MM/yyyy HH:mm:ss" or "dd-MM-yyyy HH:mm:ss" or "MM-dd-yyyy HH:mm:ss" etc. I want to convert them into timestamp and display them in UI. I tried below code for getting date object

new Date("05/01/2012 21:10:17");
Tue May 01 2012 21:10:17 GMT+0530 (India Standard Time)
new Date("15/01/2012 21:10:17");
Invalid Date
new Date("15-01-2012 21:10:17");
Invalid Date
new Date("05-01-2012 21:10:17");
Tue May 01 2012 21:10:17 GMT+0530 (India Standard Time)

Few of them are getting Invalid Date. Please help me, is there any specific code/logic to convert any string format to date object?

Nagarjuna Reddy
  • 4,083
  • 14
  • 41
  • 85

3 Answers3

0

Javascript Date object reads "month day year", not "day month year", so you need to update your String a bit.

Here, I just swap the month and the day in your String :

const data = "15/01/2012 21:10:17";
const readableDate = data.substring(3,6) + data.substring(0,2) + data.substring(5,data.length);
console.log(new Date(readableDate));
Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • The built-in parser is only required to support the [subset of ISO 8601](http://ecma-international.org/ecma-262/8.0/#sec-date-time-string-format) noted in ECMA-262, support for any other format is implementation dependent. – RobG Apr 17 '18 at 20:41
0

There is the best tool for playing with dates in JavaScript I've been ever using. It's called Moment.js. I recommend you to take a look at this, it allows you for example to do something like this:

var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
var myDate = moment(str, 'YYYY-MM-DD').toDate();
Dawid Rutkowski
  • 2,658
  • 1
  • 29
  • 36
0

You can also do this:

var d = new Date(year, month, day, hour, minute, second, millisecond);

To convert to timestamp you call:

d.getTime()
Iago Bruno
  • 702
  • 1
  • 7
  • 15