Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Date(..).getTime() is not equal to moment(..).valueOf() in momentJS?

Tags:

new Date(..).getTime() should return a timestamp in milliseconds. According to the documentation of momentJS the expression moment(..).valueOf() should do the same (return timestamp in milliseconds for a given date).

I checked with the following example data:

var timeStampDate = new Date("2015-03-25").getTime(); //timestamp in milliseconds? > 1427241600000 var timeStampMoment = moment("03-25-2015", "MMDDYYYY").valueOf(); //timestamp in milliseconds? > 1427238000000 

As you can see the results were not the same.

Now I'm searching for a function in momentJS that returns to me the exact same data that the expression new Date(..).getTime().

like image 765
thadeuszlay Avatar asked Jul 14 '15 08:07

thadeuszlay


People also ask

How do you compare dates with moments?

We can use the isAfter method to check if one date is after another. We create a moment object with a date string. Then we call isAfter on it with another date string and the unit to compare. Therefore isAfter is false since we compare the year only.

What is Moment () in JavaScript?

MomentJS is a JavaScript library which helps is parsing, validating, manipulating and displaying date/time in JavaScript in a very easy way. This chapter will provide an overview of MomentJS and discusses its features in detail. Moment JS allows displaying of date as per localization and in human readable format.


2 Answers

Date constructor doc:

The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information

moment constructor doc:

Unless you specify a timezone offset, parsing a string will create a date in the current timezone

so specifying the timezone in the moment constructor results in the same behavior as Date:

var timeStampMoment = moment("03-25-2015 +0000", "MM-DD-YYYY Z").valueOf(); //> 1427241600000 
like image 104
R. Oosterholt Avatar answered Sep 18 '22 05:09

R. Oosterholt


When you pass in the same value to Date and moment (at least in Chrome a few years on), you get the same value from both values.

new Date("2015-03-25").getTime() 1427241600000 moment("03-25-2015", "MMDDYYYY").valueOf() 1427259600000 new Date("03-25-2015").getTime() 1427259600000 

What you actually hit was just a different guess of the Date format in Date.parse

like image 34
iabw Avatar answered Sep 21 '22 05:09

iabw