0

I am getting this "20131218" date/time value from an API result.

What I want to do is convert this date into something like this "2013-12-18". I know this is very easy in PHP by simply doing this code:

echo date("Y-m-d",strtotime('20131218'));

output: 2013-12-18

This is what I tried in javascript:

var myDate = new Date("20131218");
console.log(myDate);

But the output is Date{ Invalid Date } so obviously this is wrong.

My question here what is the equivalent of strtotime in javascript? or if there's no equivalent, how would I convert this value as my expected result(2013-12-18) using javascript?

Your help will be greatly appreciated!

Thanks! :)

1

3 Answers 3

1

The value is invalid to convert it to date. So either from your PHP code send it as a proper format like 20131218

Or convert the value you get in your Javascript to similar kind of format.

var dateVal="20131218"; 
/*
 // If it's number  *******   //
var numdate=20131218;
var dateVal=numdate.toString();
*/

var year=dateVal.substring(0,4);
var mnth=dateVal.substring(4,6);
var day=dateVal.substring(6,8);
var dateString=year+"-"+mnth+"-"+day;


var actualDate = new Date(dateString); 
alert(actualDate);

JSFIDDLE DEMO

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

Comments

1

Javascript has a Date.parse method but the string you have is not suitable to pass to it. You don't really need to create a date object just to format a string. Consider:

function formatDateStr(s) {
    s = s.match(/\d\d/g);
    return s[0] + s[1] + '-' + s[2] + '-' + s[3];
}

alert(formatDateStr('20131218')); // '2013-12-18'

If you wish to convert it to a date object, then:

function parseDateStr(s) {
    s = s.match(/\d\d/g);
    return new Date(s[0] + s[1], --s[2], s[3]);
}

Comments

0

The reason why it is showing Invalid date is, it wants it to be in format

Following format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS

If you breakdown your string using following format just add dash at relevant places then you are good to go and use newDate.

1.    var myDate = new Date("2013-12-18"); 
      alert(myDate);

2.    var myDate = new Date(2013,12,18);

Eventually you can modify your string manipulate it and use it in aforementioned format.

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.