Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JavaScript getTime() is not a function?

I used the following function:

function datediff() {   var dat1 = document.getElementById('date1').value;   alert(dat1);//i get 2010-04-01   var dat2 = document.getElementById('date2').value;   alert(dat2);// i get 2010-04-13     var oneDay = 24*60*60*1000;   // hours*minutes*seconds*milliseconds   var diffDays = Math.abs((dat1.getTime() - dat2.getTime())/(oneDay));   alert(diffDays); } 

I get the error:

dat1.getTime()` is not a function 
like image 522
udaya Avatar asked Apr 13 '10 07:04

udaya


People also ask

How does getTime work in JavaScript?

getTime() The getTime() method returns the number of milliseconds since the ECMAScript epoch. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.

Is new Date () getTime () UTC?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.

What is new Date () getTime ()?

The date. getTime() method is used to return the number of milliseconds since 1 January 1970. when a new Date object is created it stores the date and time data when it is created. When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch).

Can JavaScript handle dates and time?

The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.


1 Answers

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format function parseDate(input) {   var parts = input.match(/(\d+)/g);   // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])   return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based } 

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

like image 137
Christian C. Salvadó Avatar answered Oct 11 '22 12:10

Christian C. Salvadó