How would I get the millisecond from January 1st 00:00:00:000 (of this year) with Javascript? For example, January 1st 00:00:00:000 would give me 0 and December 31st 23:59:59:999 would give me 31536000000.
Asked
Active
Viewed 187 times
1
-
1make a [Date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) for that time and call `.getMilliseconds()` ? – Pointy Nov 13 '14 at 22:12
-
1"December 31st 23:59:59:999 would give me 31,536,000,000". Or 31,622,400,000 if it was a leap year, presumably? – Boann Nov 13 '14 at 22:14
-
1So what have you tried? – Lightness Races in Orbit Nov 13 '14 at 22:16
-
1wait, do you want from Jan 1st of THIS year? or from Jan 1 1970? – scunliffe Nov 13 '14 at 22:18
-
1Sorry with the lack of details with my question. I wanted from Jan 1st of THIS YEAR. I tried working out some math (24*60*60*1000 and stuff) but it gave me wrong numbers. – Tetsudou Nov 13 '14 at 23:11
-
As noted by @Tetsudou and Boann this is not a duplicate. The OP wants the time diff in milliseconds from the beginning of "this" year - not Epoch Time. – scunliffe Nov 13 '14 at 23:49
2 Answers
3
This will get you a new date (now) as ms from Jan 1st 1970. (Epoch Time)
var ms = new Date().getTime();
If you want it from Jan 1st of this year you can use.
var janFirstThisYear = new Date('1/1/2014').getTime();
var now = new Date().getTime();
var ms = now - janFirstThisYear;
Note: this is hard coded to the year 2014. Depending on your needs this could be re-worked to automatically extract 'this' year.
e.g.
var now = new Date();
var thisYear = now.getFullYear();
var janFirstThisYear = new Date(thisYear, 0, 1);
var ms = now.getTime() - janFirstThisYear.getTime();

scunliffe
- 62,582
- 25
- 126
- 161
-
-1 for your quick response without specifying 1970 - I evened it out after your edits :P – Shaded Nov 13 '14 at 22:22
-
thanks @Shaded (yeah I didn't know if the OP wanted this year only, or from "all time" ;-) – scunliffe Nov 13 '14 at 22:23
-3
For example:
x = new Date; x.getMilliseconds();

user4245863
- 5
- 1
-
This has absolutely nothing to do with the question. This gets the milliseconds of the *current time* (i.e. Nov 13 4:26:___), not the time in milliseconds since a certain date. (Therefore, it always returns a number from 0 to 1000.) – tckmn Nov 13 '14 at 22:27