3

In javascript, how can I get three different substrings for the date, month, and year from the following string: "12/15/2009" ?

8 Answers 8

12
var date = "12/15/2009";
var parts = date.split("/");

alert(parts[0]); // 12
alert(parts[1]); // 15
alert(parts[2]); // 2009
Sign up to request clarification or add additional context in comments.

Comments

4

You can use the .split() method to break apart the string.

var strDate = "12/15/2009";
var arrDate = strDate.split('/');

var month = arrDate[0];
var day = arrDate[1];
var year = arrDate[2];

Comments

3

If you want to do any more complex date manipulation, you can also convert the string to a JavaScript Date object like this:

var date = new Date("12/15/2009");
alert(date.getFullYear());
alert(date.getMonth() + 1);
alert(date.getDate());

var newYear = new Date("1/1/2010");
alert((new Date(newYear - date)).getDate() + " days till the new year");

Comments

2

Do you want, "12","15", and "2009"? if yes following would return 3 string array.

"12/15/2009".split("/")

Comments

1

Try the following:

var dateString = "12/15/2009";
var dateParts = dateString.split("/");
var month = dateParts[0];
var day = dateParts[1];
var year = dateParts[2];

Comments

1
var splitDate = "12/15/2009".split("/");
var month = splitDate[0];
var day = splitDate[1];
var year = splitDate[2];

Comments

1

try using [yourstring].split(char splitter) to achieve the desired result (i.E. date.split("/")). This will yield a string array.

Comments

1

You can use split to split the string :

var list = "12/15/2009".split('/');
var year = list[2];
var month = list[0];
var day = list[1];
console.log(day, month, year);

Will get you :

15 12 2009

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.