0

How would you convert a European String date "13/05/2015 12:00:00 PM" to a JavaScript Date object? Remember that the Date constructor expects the year or the month to come first, not the day.

We need to swap the day and month before creating the Date, but I'm after a better way than string manipulation and I'm not inclined to use a 3rd party library.

Ideas?

ChrisRich
  • 8,300
  • 11
  • 48
  • 67
  • why aren't you inclined? libraries like http://momentjs.com/ are meant to avoid such busywork – svarog May 13 '15 at 08:33
  • Oh, don't get me wrong, usually I wouldn't mind using a library, especially Moment since it's really good. But I didn't feel like using a library for a single task and wanted to explore other options first. But it seems there are no better ways than string manipulation in this case (or using Moment) – ChrisRich May 15 '15 at 04:21

1 Answers1

0

There is probably a more elegant way to do that, but you can achieve it with split in a dozen lines of code. It's still string manipulation, so it's probably not what you're asking for.

Don't forget to read again how JS Dates works (the important thing is that months in JS go from 0 to 11).

Some code I made for you:

var euroStringDate = "13/05/2015 12:00:00 PM";
var splitDateTime = euroStringDate.split(' ',2); //separate date and time
var splitDate = splitDateTime[0].split("/"); //separate each digit in the date
var splitTime = splitDateTime[1].split(":"); //separate each digit in the time
var day = splitDate[0];
var month = splitDate[1] - 1; //JS counts months from 0 to 11
var year = splitDate[2];
var hour = splitTime[0];
var min = splitTime[1];
var sec = splitTime[2];
var d = new Date(year,month,day,hour,min,sec,0); //place the pieces in the correct order

And here's a jsfiddle.

Tom Solacroup
  • 46
  • 4
  • 18