3

Which format does java script support and why :-

I used :

Date.parse (23/01/2015) - It shows NAN
Date.parse (11/01/2015) - gives certain value.

My application have date format :- day/month/year. How to parse in this format.

2

2 Answers 2

3

Actually, Date.parse is not what you were looking for. It returns a timestamp integer value. You want new Date(string) constructor, which builds a Date JavaScript object:

document.body.innerText = new Date('01/01/2016').toString();

However, JavaScript does work with mm/dd/yyyy format by default.
For parsing dd/mm/yyyy you will have to implement your own parser using String.prototype.split and new Date(year, zeroBasedMonth, day) constructor:

function parseDdmmyyyy(str)
{
  var parts = str.split('/');
  return new Date(parts[2], parts[1] - 1, parts[0]); 
}

document.body.innerText = parseDdmmyyyy('24/11/2015');

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

Comments

2

Date.parse need a string parameter:

Date.parse("11/01/2015")

This line give you a TimeStamp

But to get a valid date you need to pass the format MM-DD-YYYY

So split the string and transform the format like :

var date = "11/01/2015".split("/");
var goodDate = date[1] + "-" + date[0] + "-" + date[2]

After you can use the Date object like :

var obDate = new Date.parse(goodDate);

With the object, you can get the month/day/year separately :

var day = obDate.getDate(); // Get the day 
var month = obDate.getMonth() + 1; // The month start to zero
var year = obDate.getFullYear();// Get the year 

console.log( day + "/" + month + "/" year );

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.