1

I have this date string "2013:05:12 11:41:31"

I tried:

var strDate = "2013:05:12 11:41:31";
var dateParts = strDate.split(":");

var date = new Date(dateParts[0], (dateParts[1] - 1), dateParts[0]);

But the former failed.

var strDate = "2013:05:12 11:41:31";
var dateParts = strDate.split(" ");
var ymd = dateParts[0];
ymd = ymd.split(":");
var hms = dateParts[1];
hms = hms.split(":");
var date = new Date(+ymd[0],ymd[1]-1,+ymd[2], hms[2], hms[1], hms[0]);

This gives me the following date and time: Mon May 13 07:41:11 CEST 2013

How do I get a JavaScript Date and Time object from it?

2
  • Spliting by : will not work in ur code. Because by seeing ur date string i have noticed that there is space between date and time. So do split by space now i have only date.. use it. Commented Jan 12, 2014 at 16:14
  • var splitedArr = strDate.split(" "); var date = splitedArr[0]; Commented Jan 12, 2014 at 16:17

3 Answers 3

1
var strDate = "2013:05:12 11:41:31";

/*
You can parse a string, but it has to be a single string argument.

An array of arguments needs to be numbers, which are easy to coerce.
avoid leading 0s- 08 and 09 can cause octal problems for some users.

*/

var ymd = strDate.match(/[1-9]\d*/g);
var day= new Date(+ymd[0],ymd[1]-1,+ymd[2]);
day.toLocaleDateString()

// returned (String) value: Sunday, May 12, 2013

Without a timezone you don't have a particular date, just May 12 wherever you are.

Javascript defaults to the users local settings, but some applications default to GMT.

Sign up to request clarification or add additional context in comments.

Comments

1
var strDate = "2013:05:12 11:41:31";
var dateParts = strDate.split(" ");
dateParts = dateParts[0];
dateParts = dateParts.split(":");

var date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);

alert(date);

First get the date, then split it and then put it in the date object.

Comments

0

You might consider using moment.js for this.

var strDate = "2013:05:12 11:41:31";
var date = moment(strDate, "YYYY:MM:DD HH:mm:ss").toDate();

1 Comment

I do not want to use another external lib.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.