How to get month from string in javascript

I have a date in a line: var myDateStr='1431451872338.00';

I want getMonth () from this format date, I do: var date = new Date(myDateStr);

but always return the wrong date.

and the getMont () method always returns NaN if I put this: var date = new Date(1431451872338.00);

this will return the date correctly, but with my string it doesn't

my var myDateStr gets the value from json and is a variable, if someone can help me, thank you in advance, I hope you can understand

+3


source to share


5 answers


Could you please use parseInt and do something like this:



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

      

0


source


This works great for me. You just need to make sure that you are entering 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

      

+1


source


An object

A Date

cannot be created using a string. Better to convert the string to first Int

and then query for the month:

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

      

+1


source


When you pass a date string to a javascript date object, it should be in the format "yyyy / mm / dd" or something like "Jan 10, 2014". What you are going through is the number of milliseconds since Jan 1, 1970 that is only accepted by the date object as a number. You need to change the type of the input variable.

Please be sure to research carefully before answering questions - the answer to your question is clearly indicated in many date references such as this one .

0


source


One liner

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

      

0


source







All Articles