1

I'm trying to get a timestamp to make a filename unique, but the Date object doesn't seem to be working as described.

var today = new Date();
var result = ui.alert(today.now());

This returns 'undefined'

var today = new Date();
var result = ui.alert(today);

returns a long formatted date string: Wed Aug 23 2017 11:40:13 GMT-0700 (PDT)

how do I get the number of milliseconds since the epoch? Isn't this what the now() method is supposed to give?

Thanks,

  • Possible duplicate of [Calculating milliseconds from epoch](https://stackoverflow.com/questions/9011758/calculating-milliseconds-from-epoch) – abagshaw Aug 23 '17 at 18:46

3 Answers3

1

You could use Date.parse which parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

console.log(Date.parse('Wed Aug 23 2017 11:40:13 GMT-0700 (PDT)'));

Or as alternative (please note the + operator returns the numeric representation of the object):

console.log(+new Date('Wed Aug 23 2017 11:40:13 GMT-0700 (PDT)'));
GibboK
  • 71,848
  • 143
  • 435
  • 658
0

Instead of parsing the output string, have you tried simply casting the Date object to a number?

var result = ui.alert(+today);
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

Date.now() is static. Use it on Date instead of the today instance.

If you want the milliseconds on a instance of date, use getTime() instead.

So:

var today = Date.now();
var result = ui.alert(today);

or

var today = new Date();
var result = ui.alert(today.getTime());

https://jsfiddle.net/k_24/qof04cvc/

Edit: it wouldn't make sense to use now() on something that was created in the past ;)

DereckM
  • 274
  • 2
  • 11