I want to get current time in UTC, substract it from ISO UTC string which I'm getting from backend in the following format: 2016-11-29T17:53:29+0000 (ISO 8601 date, i guess?) and get an answer in milliseconds.
What is the shortest way to do it in javascript? I'm using angular 2 and typescript frontend.
You can get the current time using:
var now = Date.now()
And convert the string to a milliseconds timestamp using:
var ts = (new Date('2016-11-29T17:53:29+0000')).getTime()
And then subtract the values:
var diff = ts - now
Related
How can I get the timestamp after manipulating days in Moment.js?
I tried use:
var a = moment().subtract(10, 'days').calendar().getTime()
to get the timestamp, but failed.
It is not really clear what you mean by "timestamp".
To get the number of milliseconds since the Unix epoch, use moment().valueOf();. This corresponds to JS Date.getTime();.
To get the number of seconds since the Unix epoch, use moment().unix();.
To get the hour/minute/second as numbers, use moment().hour(); / moment().minute(); / moment().second();.
To get the ISO 8601 string (recommended for sending data over the wire), use moment().toISOString(); (e.g. "2013-02-04T22:44:30.652Z").
To print a user readable time, use moment().format();, e.g. moment().format('LTS') will return the localized time including seconds ("8:30:25 PM" for en-Us).
See moment.js - Display - Format for format specifiers.
Classic calendar formatting:
const daysBefore = moment().subtract(10, 'days').calendar();
for unix timestamp (current date minus 10 days):
const daysBefore = moment().subtract(10, 'days').unix();
Just remember, apply formatting after subtraction, as formatting returns a string, not momentjs object.
You can use moment().toDate() to get a Javascript Date object. Then you can get the timestamp with getTime().
calendar does not have method getTime(). You can format your time as follows:
let format = 'YYYYMMDD';
let a = moment().subtract(10, 'days').format(format);
console.log(a)
Try the following to get the timestamp:
moment().subtract(10, 'days')._d
try this one
moment().subtract(10, 'days').calendar().format('HH:MM:SS'); //get datetime
moment().subtract(1, 'days').calendar(); // Yesterday at 1:16 PM
UTC is of format - 1994-11-05T08:15:30-05:00
But why does Date.UTC gives a string representing milliseconds ?
How can I achieve the same in Javascript and what are the browser compatibility cases I need to take care of while doing without external library ( say moment ).
Date.UTC returns the date in the UTC/GMT timezone, as a Unix timestamp.
What you are referring to as UTC format is ISO-8601 format, and you retrieve that with the toISOString() method. For example:
var d = new Date();
var n = d.toISOString();
I'm passing back a UTC date from the server, and I need some JS to find the difference in seconds between "now" and the date passed back from the server.
I'm currently trying moment, with something like
var lastUpdatedDate = moment(utcStringFromServer);
var currentDate = moment();
var diff = currentDate - lastUpdatedDate;
problem is, this gives a very invalid answer, because UTC is coming down from the server, and creating a new moment() makes it local. How can I do a calculation with respect to full UTC so it's agnostic of any local timing?
What you aren't quite understanding is that Dates are stored as the number of milliseconds since midnight, Jan 1, 1970 in UTC time. When determining the date/time in the local timezone of the browser, it first works out what the date/time would be in UTC time, then adds/subtracts the local timezone offset.
When you turn a Date back into a number, using +dateVar or dateVar.valueOf() or similar, it is back to the number of milliseconds since 01/01/1970T00:00:00Z.
The nice part about this is that whenever you serialise dates in UTC (either as a number, or as ISO String format), when it gets automatically converted to local time by Javascript's Date object, it is exactly the same point in time as the original value, just represented in local time.
So in your case, when you convert a local date to a number, you get a value of milliseconds in UTC that you are subtracting a value in milliseconds in UTC from. The result will be the number of milliseconds that has passed between the time from the server and the time the new Date() call is made.
Where it gets tricky is when you want a timestamp from the server to not be translated to local time, because you want to show the hours and minutes the same regardless of timezone. But that is not what you need in this case.
Try this way hope it may help:
var lastUpdatedDate = moment(utcStringFromServer);
var date = Date.UTC();
var currentDate = moment(date);
var diff = currentDate - lastUpdatedDate;
I'm assuming that utcStringFromServer is something like this:
Fri, 19 Aug 2016 04:27:27 GMT
If that's the case, you don't really need Moment.js at all. If you pass that string to Date.parse(), it'll return the number of milliseconds since Jan. 1, 1970. You can then use the .toISOString() method to get the same info about right now (converted to UTC) and parse it the same way to get milliseconds since 1970. Then, you can subtract the former from the latter and divide it by 1000 to convert back to seconds.
All in all, it would look something like this:
var lastUpdatedDate = Date.parse(utcStringFromServer);
var currentDate = Date.parse((new Date()).toISOString())
var diff = (currentDate - lastUpdatedDate) / 1000.0; // Convert from milliseconds
I have a date sting that looks like this 2016-02-21T02:14:39.000000
would like to convert it to Epoch time using Javascript if possible
Try
var ts = "2016-02-21T02:14:39.000000";
var unix_seconds = ((new Date(ts)).getTime()) /1000;
console.log(unix_seconds);
getTime returns milliseconds, so divide by 1000 to get seconds
https://jsfiddle.net/tbxac0de/
Presumably by "convert it to Epoch time" you mean a number of seconds or milliseconds since the common UNIX and ECMAScript epoch. The time value can be found by converting the string to a Date and getting its internal time value.
By far the best way to convert a string to a Date is to manually parse it. A library can help, but a function isn't difficult to write. E.g. to parse "2016-02-21T02:14:39.000000" as a local date (i.e. ISO 8601 format without a time zone), use something like:
// Parse y-m-dTh:m:s as local date and time
// since there is no timezone
function parseIsoLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5],
((b[6]||'')+'000').slice(0,3));
}
// Convert string to Date
var d = parseIsoLocal('2016-02-21T02:14:39.000000');
// Show date and milliseconds since epoch
document.write(d + '<br>' + +d);
The above can easily be extended to treat the string as UTC, incorporate time zones and validate the input, but that doesn't seem to be required in this case.
Note that most browsers will parse the format in the OP, however some in use will not and, of those that will, some treat it as local and some as UTC. According to ISO 8601, it should be treated as local so that's what I've done.
I'm converting string to timestamp by using
var timestamp = new Date(month+"/"+day+"/"+year).getTime()/ 1000;
My question is how to set it as UTC timezone before converting to timestamp ?
Use the Date.UTC() method instead of .getTime().
var timestamp = Date.UTC(year,month,day) / 1000;
(Note: the month is expected to be from 0-11, not 1-12.)