48

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?

Community
  • 1
  • 1
Thunder Rabbit
  • 5,405
  • 8
  • 44
  • 82

4 Answers4

66

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

var now = Date();

try this

var now = new Date();
Simon
  • 37,815
  • 2
  • 34
  • 27
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • @clocksmith `Date.now()` (note: no parens) does work, `.getTime()` needs a Date object. Also see http://stackoverflow.com/questions/12517359/performance-date-now-vs-date-gettime Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime – handle Aug 25 '16 at 08:33
  • Awesome that it works, but my question is WHY? – SkogensKonung Mar 30 '21 at 14:16
29

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

(new Date()).getTime()
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
Simon
  • 37,815
  • 2
  • 34
  • 27
10

This will make 'now' as variable type as date:

var now = new Date();

This will get you time from 'now':

new Date(now).getTime();
Hywel Rees
  • 884
  • 1
  • 15
  • 22
loyoliteabid
  • 185
  • 2
  • 7
-1

this works: dateX is passed in as a variable of type date

fctDateToLong(dateX: Date|string|number): number 
  {
    return new Date(dateX).getTime() 
   }

I am not 100% sure why this works so will not comment on the why. Good luck.

you also try this where dateX is of Date Type.

const newDate = new Date(dateX.toString()).getTime()