3

i have a date in string like this: var myDateStr='1431451872338.00';

i want, getMonth() from this format date, i do:var date = new Date(myDateStr); but always return invalid date.

and the method getMont() always return NaN, if I put this: var date = new Date(1431451872338.00); this return the date correct but with my string not

my var myDateStr get the value from json and is variable, if someone can help me thank you very much in advance, i hope do understand

7
  • 1
    Try new Date(Number(myDateStr)) Commented May 12, 2015 at 18:35
  • If the Date is in quotes then it makes since that it would return NaN when you do the function getMont() if getMont() is expecting a number. NaN is not a number Commented May 12, 2015 at 18:35
  • @JacobFinamore typeof NaN === "number" (Yes, Javascript is funny like that) Commented May 12, 2015 at 18:45
  • FYI - Assuming your format is aligned to what the Date constructor expects, the decimals .00 are meaningless. Commented May 12, 2015 at 18:46
  • @IngoBürk Yea that would end up being true lol so would typeof NaN === "123" Commented May 12, 2015 at 18:57

5 Answers 5

1

This works fine for me. You just need to be sure you're inputing a number, not a string.

var number = parseInt("1431451872338.00");
var date = new Date(number); //Tue May 12 2015 12:31:12 GMT-0500 (CDT)
var month = date.getMonth(); // 4
Sign up to request clarification or add additional context in comments.

Comments

1

A Date object cannot be instantiated with a string. You better 1st transform your string into an Int and then ask for month:

var myDateStr='1431451872338.00';
var date = new Date(parseInt(myDateStr, 10));
alert(date.getMonth());

2 Comments

@IngoBürk that's new, never knew it. Thanks
0

Could you use parseInt and do something like this:

var myDateStr = '1431451872338.00';
var myDateInt = parseInt(myDateStr, 10);
var myDate = new Date(myDateInt);

2 Comments

Date constructor expects integer, not float
0

When you're passing in a date string to the javascript date object, it needs to be in the format "yyyy/mm/dd" or something like "January 10, 2014". What you're passing is the number of milliseconds since January 1, 1970, which is only accepted by the date object as a number. You need to change the type of your input variable.

Please make sure to research carefully before answering questions - the answer to your question is clearly stated on many date references like this one.

Comments

0

One Liner

var month = date.getMonth(Date(parseInt("1431451872338.00")));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.