0

i'm trying to get a local timestamp in a controller that won't be used in a view (ie filter not an option)
(for info it's to be written into an SQLite db as a local 'date created' field)

the following gets me the date - but is in the wrong format:

var current_time = new Date();
console.log('current_time:', current_time);

which gives me date in the format current_time: Thu Dec 18 2014 23:16:27 GMT-0800 (PST)

the following also works (which partially solves my problem - since i think i can use UTC):

var current_time = new Date().getTime();
console.log('current_time:', current_time);

which gives current_time: 1418973515745 however it's UTC according to the docs

however this (which i thought was the solution) does not work:

var current_time = new Date.now();
console.log('current_time:', current_time);

gives me the following error:
TypeError: function now() { [native code] } is not a constructor

according to the javascript docs I've got the right formats etc...
the Angular docs don't mention anything specific (mostly seems to be how to get from timestamp to human readable, not the other way around)

so for curiosity:

  • is there any reason Date.now() shouldn't work in Angular? ..am I writing something wrong ?
  • why would Date().getTime() work but Date.now() not ?
  • how do i get local js timestamp variable in Angular without using a filter ? ...and without using a separate longwinded directive as suggested in AngularJs get Timestamp from a human readable date
Community
  • 1
  • 1
goredwards
  • 2,486
  • 2
  • 30
  • 40
  • 1
    To save one character space, instead of doing `Date.now()`, you can do `+new Date` which is the same ;) – Derek 朕會功夫 Dec 19 '14 at 08:00
  • 1
    Both `new Date().getTime()` and `Date.now()` will return exactly the same value: milliseconds since the (UTC) epoch. – RobG Dec 19 '14 at 08:23
  • @RobG - yes you're right... read the docs again and there's UTC plain as day :-/ looks like I'll go with my UTC option :-) – goredwards Dec 19 '14 at 08:30
  • 1
    @Derek朕會功夫—but *Date.now()* should be more efficient as it doesn't create a Date instance, then do type conversion. The difference might be trivial, but so is saving 1 character. ;-) – RobG Dec 19 '14 at 13:29

2 Answers2

3

You don't use new with Date.now(), it's just:

var current_time = Date.now();

As the error message is telling you, Date.now isn't a constructor function.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

rookie error:

it was the "new" that was causing the problem: this works fine

var current_time = Date.now();
console.log('current_time:', current_time);

output = current_time: 1418974955726

goredwards
  • 2,486
  • 2
  • 30
  • 40