Get current unix time in milliseconds in javascript - javascript

Hi this is incredibly simple i cant believe im asking this.
I have tried the following:
Moment.now()
Date.now()
new Date().valueOf()
And various other tricks found in other stack overflow questions
They all give me the time in microseconds.
e.g
1543409290654
which is 09/10/50878 # 10:57am (UTC)
Im aware i could divide by 1000 but surely there is an api in javascript to get the unix timestamp in milliseconds.
Ive have seen this in chrome and react native
EDIT:
So i realise my stupidity i was putting the unix timestamp into a website that renders it as an ISO date but it was expecting seconds which is why i thought my dates were coming in as milliseconds

Date.now() returns the number of milliseconds since midnight January 1, 1970

There is no native javascript to format time into unix-timestamp.
I found this useful
var today = Math.round((new Date()).getTime() / 1000);
console.log(today);

Related

Simplest way to find out how many milliseconds until a specific time in a specific timezone (taking DST into account)?

I have a piece of code which finds the difference between two dates(in the format of yyyy-MM-dd hh:mm:ss) . This code is run in multiple servers across the globe. One of the two dates is the current time in that particular timezone where the code is being run(server time) and another is the time obtained from a database. if the difference between these two times is greater than 86400 seconds(1day), then it should print "invalid" else, it should print "valid".
Problem im facing with the code is when I run it on my local, its working fine, but when i deploy it onto a server in US, its taking GMT time into consideration and not local time.
Wherever the code is run, I want the difference between current time and time fetched from the database, and if its greater than 86400 seconds, i want to print invalid. How to achieve this in java?
PS: I tried with Date object, but its considering GMT only everywhere.
I would use GMT everywhere and only convert to the local times for display purposes.
To find the difference, convert both times to the same timezone (say GMT) and take the difference.
You can do it by the below example code.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date1 = dateformat.parse(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
Date date2 = dateformat.parse(formatter.format(date));
// Prints the date in the IST timezone
// System.out.println(formatter.format(date));
Now compare date1 with date2
First, I concur with Peter Lawrey's answer up there. It is usually good practice to store all time in the database for a single zone, and render it with offset for the user based upon the user's locale.
To find the difference, use the method getTime() to get the time in milliseconds from the epoch for each date. The calculation for the difference of 1 day is then 86400 * 1000 milliseconds. Or, perhaps, store the time in milliseconds from epoch in the database, and use a DB procedure/function at the time of retrieval.
Hope this helps.

What is the difference between Date.now and Date.getTime in Javascript and how timezone affects them?

I am trying to understand how creation of dates using Javascript on client and server both can affect query results when timezone of client and server can differ.
On client side, I am using Date.now() to save timestamp information
var time = Date.now()
console.log(time);
The now() method returns the milliseconds elapsed since 1 January 1970
00:00:00 UTC up until now as a Number.
My understanding is that this timestamp is independent of any timezone offset, in other words it points to time at Zero timezone offset. Is it correct?.
We can also get this timestamp using the following code
var now = new Date();
time = now.getTime();
console.log(time);
This code still gives the same timestamp information (at zero timezone offset). Is Date.now() just a quick way to get timestamp?
Now, constructing date from Date.now() and displaying it in browser's console.
var time = Date.now()
console.log(time);
var date = new Date(time)
var time = date.getTime()
console.log(time);
console.log(date);
In my opinion, it is only when displaying in browser's console, date is formatted in the browser's local timezone otherwise this date instance still holds timestamp at zero timezone offset. Is it correct?.
I have also seen an answer of converting Javascript date to UTC
var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
time = now_utc.getTime();
console.log(time);
This code still gives the same timestamp information as given by Date.now() and console.log statements were differing by few milliseconds only which I think is due to code execution time instead of any timezone difference. When executed, following was the output for that instance of time:
1468408292575
1468388492000
Is there any difference between a UTC timestamp and timestamp given by Date.now()?
Can you please confirm if these three options produce same result (i.e. independent of any timezone) and if it is safe to use this timestamp information for client and server interactions when they are in a different timezone. Examples:
Client sends a save request to server side to save this client side generated timestamp?
Client asks for results based on this saved timestamp?
I want to reduce this to a level where I want to show timezone information only for display purpose e.g. in HTML, in generated files.
My questions might be too simple because I am confused on seeing the Date class documentation on correctly using it to avoid time difference issues.
both are typically same, but Date.now() is little faster
Further Reading:
Performance - Date.now() vs Date.getTime()
Performance .now() vs Date.now()
I posted an answer on date and timezone related question. Answer says that the internal recording of the date generated on client side are at zero timezone offset. Just adding answers to individual questions:
My understanding is that this timestamp is independent of any timezone
offset, in other words it points to time at Zero timezone offset. Is
it correct?.
Yes
This code still gives the same timestamp information (at zero timezone
offset). Is Date.now() just a quick way to get timestamp?
Yes
Is there any difference between a UTC timestamp and timestamp given by Date.now()?
No

How to convert 12 hours datetime to timestamp with javascript

I have a datetime in following format 28/11/2015 09:41 PM and I want to convert it to epoch timestamp. How can I do that with javascript?
Additionally: I want to add and substracts 7200 seconds from that timestamp and convert it back to the original format. How can I do that? Is it necessary to convert datetime to timestamp first?
There is an awesome library available for that!
http://momentjs.com/
A great place to find information on JavaScript's built-in objects is the MDN, which has this article (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) on the datetime (or really just Date) object.
The way to get an epoch timestamp from a Date object is to use the getTime() function. It returns the number of milliseconds since 1 January, 1970.
var dateNow = Date.now();
var epochNow = dateNow.getTime();
You can then just add the seconds to it:
epochNow += (7200 * 1000); // * 1000 because it's in milliseconds
And then convert it back:
dateNow.setTime(epochNow);
Good luck!
NOTE
Beware inconsistencies in JavaScript Date implementations, especially in earlier versions of Internet Explorer. As some have noted, a good library like moment.js (http://momentjs.com/ ) is very helpful to prevent problems. However, if you are only using fully modern browsers or node, you shouldn't have as many problems.

Reliable way to convert javascript timestamp into a date tuple

I want to convert javascript time stamps to erlang dates. I am using the qdate library to help me do that since it also provides functions for date arithmetic.
Calling it's to_date function first before midnight and then after midnight results in time displacement of 24 hrs. For example:-
qdate:to_date(Timestamp div 1000).
%% {2015,5,2} before midnight
qdate:to_date(After_midnight_Timestamp div 1000)
%%{2015,5,2} after midnight should be 3 instead of 2
I googled around a bit and found this in the erlang calender docs
The time functions local_time/0 and universal_time/0 provided in this module both return date and time. The reason for this is that separate functions for date and time may result in a date/time combination which is displaced by 24 hours. This happens if one of the functions is called before midnight, and the other after midnight. This problem also applies to the Erlang BIFs date/0 and time/0, and their use is strongly discouraged if a reliable date/time stamp is required.
I am having trouble understanding this. Which one of the functions from local_time/0 and universal_time/0 always gives the correct results? By correct I mean I want the right date to be shown after midnight. The resolution of the time is only {y,m,d}. Don't care for hours, minutes and seconds or anything finer than that.
So how do I reliably convert a javascript timestamp to a date in erlang?
Looks like it was just a timezone issue :) Since I was working with javascript timestamps the default timezone of the javscript time stamp is my localtimzone which is "IST". Now internally when qdate sees an integer in qdate:to_date(Timestamp). it automatically selects a UTC timezone for it. Relevant code on line 256:-
raw_to_date(Unixtime) when is_integer(Unixtime) ->
unixtime_to_date(Unixtime);
%% other clauses
and on line 654
unixtime_to_now(T) when is_integer(T) ->
MegaSec = floor(T/1000000),
Secs = T - MegaSec*1000000,
{MegaSec,Secs,0}.
unixtime_to_date(T) ->
Now = unixtime_to_now(T),
calendar:now_to_datetime(Now).
The final clue comes from the erlang calendar documentation itself
now_to_datetime(Now) -> datetime1970()
Types: Now = erlang:timestamp()
This function returns Universal Coordinated Time (UTC) converted from the return value from erlang:now().
So the solution to this problem was to simply supply an IST string with qdate:to_date() like so:-
qdate:to_date("IST",Timestamp div 1000)
and it started returning correct dates. I wasn't sure of the solution so I ran a test with qdate:to_date(erlang:now()) and the value returned was exactly 5:30 hrs behind my clock time. So it seems that supplying the timezone string works :)

Daylight savings time and JavaScript timezone conversions

I have this dilemma with JavaScript. I need to convert a list of dates from client's local timezone to NYC (EST) timezone. I'm using the function below:
Date.prototype.toNycTime = function() {
var localTime = this.getTime();
var localOffset = this.getTimezoneOffset() * 60000;
var utc = localTime + localOffset;
this.setTime(utc - 3600000 * 5);
return this;
};
It works OK. One problem is that I need to adjust UTC offset every time there's a daylight saving switch in USA. And that works OK for any date that is before the next switch (earliest coming is 13-MAR-2011). But it doesn't work on dates after the switch. I don't know of any build-in JS function in any of the browsers that will do the conversion for me.
Is there a good library out there that will allow me to do some universal conversions? Or can anyone offer any tips on the code above? I'm trying to avoid programming in the dates/times for the conversion and having to look up all the time.
I'm dealing with this exact problem... corporate users throughout the world, but 'corporate time' is PST/PDT which includes daylight saving time.
How I've been approaching it:
I actually parse a POSIX timezone string for PacificTime starting with
PST8PDT,M3.2.0/2,M11.1.0/2
and reformat those into parseable date strings for when clocks more forward and back.
Using the hours-offset embedded in the TZ string, I convert the forward and back times to epoch timestamps and use an if-then to calculate if corporate time is currently DST.
This yields an offset from UTC I can use to convert local 'epoch' times (which are already in UTC) to a conceptual localtime (that is actually converted in UTC time, but looks local).
I have to do this as 'flot' does everything in UTC
http://www.datejs.com/
Datejs is an open-source JavaScript Date Library.
Comprehensive, yet simple, stealthy and fast. Datejs has passed all trials and is ready to strike. Datejs doesn’t just parse strings, it slices them cleanly in two.

Categories