Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Date().getTime() is not a function

I'm trying to compare some Dates in javascript.

For some reason, I'm getting "Tue May 01 2012 16:43:03 GMT+0900 (JST) has no method 'getTime'"

Of course, strings don't have methods

I started with this code inside a callback, but it was failing at getTime() on the line that creates var age:

for (var i = 0; i < array_of_usage_indices.length; i++) {     store.get(array_of_usage_indices[i]['key'],function(may_need_gc) {         if(may_need_gc) {             var now = Date();             var created = Date(may_need_gc['value']);             var age = now.getTime()-created.getTime();         }     }) } 

I've pared it down so my example page is literally just this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">     <head>         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />         <title>date test</title>      </head>  <body>  <script type="text/javascript" charset="utf-8">             var now = Date();             alert(now.getTime());             var t = Date().getTime(); </script>     </body> </html> 

This is failing in Chrome 18.0.1025.168 and Firefox 13.0.

Screenshots of what I've tried:

screenshot no method 'getTime'

screenshot no method 'getTime'

So my question:

wth?

Do I have to use ParseDate()? Why isn't this working?

like image 612
Thunder Rabbit Avatar asked May 01 '12 08:05

Thunder Rabbit


People also ask

What does Date getTime () do?

Javascript date getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another Date object.

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 does getTime return Date?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.


2 Answers

Try using new keyword to instantiate a new object so instead of this

var now = Date(); 

try this

var now = new Date(); 
like image 138
Parv Sharma Avatar answered Sep 25 '22 11:09

Parv Sharma


You need to use the new operator to create a Date object.

(new Date()).getTime() 
like image 31
Simon Avatar answered Sep 22 '22 11:09

Simon