Convert UTC time into IST time in node js [duplicate] - javascript

This question already has answers here:
Generating a date in a particular timezone [duplicate]
(2 answers)
Converting unix date-timestamp to time for a particular timezone in javascript
(2 answers)
Closed 5 years ago.
I have UTC time 1502212611. I have to convert it to 2017-08-08 17:16:51. But when I use the code below I am getting 2017-08-08T17:16:51.000Z.
var utc = 1502212611;
var utcSeconds = utc;
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
console.log(d);

You can use moment.js, as others have already suggested.
But in your question is not clear if you want the output as UTC or IST (the question title says "Convert UTC to IST", but in the question the desired output (2017-08-08 17:16:51) is the corresponding UTC date/time).
Anyway, if you want the output in UTC, you can do this:
var utc = 1502212611;
var m = moment.unix(utc).utc().format('YYYY-MM-DD HH:mm:ss');
console.log(m);
The unix method takes a value of seconds since epoch (1970-01-01T00:00Z). Then the utc() method makes sure the date will be formatted as UTC (if you don't call it, the date will be displayed using the default timezone, which can vary according to your system).
The output will be:
2017-08-08 17:16:51
If you need to convert to IST, you'll need to also use moment timezone:
var utc = 1502212611;
var m = moment.unix(utc).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss');
console.log(m);
The tz method converts the date to another timezone. The rest of the code is similar to the previous one.
The output will be:
2017-08-08 22:46:51
Note that I used Asia/Kolkata instead of IST. That's because the API uses IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard - IST can be "India Standard Time", "Israel Standard Time" or "Irish Standard Time", and the API can't deal with such ambiguity (the code above won't work with IST, so you must use a proper timezone name).
You can get a list of all available timezones names (and choose the one that fits best to your case) by calling moment.tz.names().
In plain Javascript, you must do it manually:
// pad zero if value <= 9
function pad(value) {
return value > 9 ? value: "0" + value;
}
var utc = 1502212611;
var d = new Date(0);
d.setUTCSeconds(utc);
var m = d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate())
+ ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes())+ ':' + pad(d.getUTCSeconds());
console.log(m);
Output:
2017-08-08 17:16:51

You can use moment if you have a moment .
momenttime = moment()
momenttime.format("YYYY-MM-DD hh:mm:ss ")

Related

Javascript dates are a day off? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Changing the format of a date string
(2 answers)
Closed 5 years ago.
I am trying to use a simple date function in my application to pass a date in the format of yyyy-mm-dd such as 2017-07-30 and have it returned in the format of 07/30/2017.
However, when I try this, I supply my date correctly but it outputs one day shorter than what I am looking for.
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
var day = date.getDate().toString();
var month = (date.getMonth() + 1).toString();
// Months use 0 index.
return (month[1] ? month : '0' + month[0]) + '/' +
(day[1] ? day : '0' + day[0]) + '/' +
date.getFullYear();
}
}
console.log(format('2017-07-30'));
Here is a fiddle: http://jsfiddle.net/49pptrj4/
Any thoughts as to why this is returning incorrectly?
Result on my end:
From here
Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.
Your date string is assumed to be 0:00, or midnight, on the date specified in UTC, the time zone of Greenwich, England. Your browser however takes this time and converts it to your local timezone, which is a few hours behind UTC if you're in the Americas, making the result a day behind.
The following code should work for creating a Date in the local timezone with the correct date.
utcDate = new Date("2017-07-30"); //Date object a day behind
new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000) //local Date
Here the local Date is created by adding time based on the time zone difference. getTimezoneOffset() returns in minutes, so * 60000 is needed to convert to milliseconds.
This might not work in areas ahead of UTC; it might advance an extra day.
Edit: Just checked and getTimezoneOffset() is negative in areas ahead of UTC so it will subtract time correctly.

Javascript - converting local time to google friendly UTC time

I want to get the date and time from 2 text boxes and format them and send them to the Google directions javascript API to get transit directions.
How do I add the date and time values together and then convert them to standard UTC time?
This is what i have:
var dateOfTravel = document.getElementById('fdate').value;
var timeOfTravel= document.getElementById('ftime').value;
//join the date and time strings
var d1 = new Date(dateOfTravel + ' ' + timeOfTravel);
alert("date and time is " + d1);
alert(d1.getTime());
var UTCDateAndTime = moment(d1).unix();
alert(UTCDateAndTime);
thanks,
Tom
Several options:
JavaScript dates have toISOString, which provides a standard ISO-8601 date/time string always in UTC, e.g. "2015-10-25T11:02:23.019Z". (Yes, the timezone specifier is always Z, that's required by the spec. So it doesn't vary by locale or timezone.)
You can use the various getUTCXyz methods to build your own string.
getTime returns the number of milliseconds since The Epoch (Jan 1 1970 at midnight UTC), which is not timezone-dependent.
getTimezoneOffset tells you how far offset you are from UTC, which you could use to adjust things (though I can't see a good reason for that in this case).
This appears to be working:
var d1 = new Date(dateOfTravel + ' ' + timeOfTravel);
//if the year is less than 1970 then add 100 on. Using 2 digit years and there's a bug with javascript date implimentation
if (d1.getFullYear() < 1970) {
d1.setFullYear(d1.getFullYear() + 100);
}

Using momentjs to convert date to epoch then back to date

I'm trying to convert a date string to epoch, then epoch back to the date string to verify that I'm providing the correct date string.
var epoch = moment("10/15/2014 9:00").unix(); // do I need to do .local()?
var momentDate = moment(epoch); // I've also tried moment.utc(epoch)
var momentDateStr = momentDate.calendar();
alert("Values are: epoch = " + epoch + ", momentDateStr = " + momentDateStr);
Renders
Values are: epoch = 1413378000, momentDateStr = 01/17/1970
Note: I'm using the following version of the moment js script, //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment-with-locales.js
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local() or .utc().
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
http://momentjs.com/docs/#/displaying/unix-timestamp/
You get the number of unix seconds, not milliseconds!
You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.
moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

How do I format a date as ISO 8601 in moment.js?

This docs mention moment.ISO_8601 as a formatting option (from 2.7.0 - http://momentjs.com/docs/#/parsing/special-formats/), but neither of these work (even 2.7.0):
var date = moment();
date.format(moment.ISO_8601); // error
moment.format(date, moment.ISO_8601); // error
(http://jsfiddle.net/b3d6uy05/1/)
How can I get an ISO 8601 from moment.js?
moment().toISOString(); // or format() - see below
http://momentjs.com/docs/#/displaying/as-iso-string/
Update
Based on the answer: by #sennet and the comment by #dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.
I've opened an issue as I think it can lead to unexpected results.
Use format with no parameters:
var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"
(http://jsfiddle.net/8gvhL1dz/)
Also possible with vanilla JS
new Date().toISOString() // "2017-08-26T16:31:02.349Z"
When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.
moment.format()
2018-04-17T20:00:00Z
moment.toISOString() -> USE THIS TO STORE IN MONGOOSE
2018-04-17T20:00:00.000Z
var date = moment(new Date(), moment.ISO_8601);
console.log(date);
If you just want the date portion (e.g. 2017-06-27), and you want it to work regardless of time zone and also in Arabic, here is code I wrote:
function isoDate(date) {
if (!date) {
return null
}
date = moment(date).toDate()
// don't call toISOString because it takes the time zone into
// account which we don't want. Also don't call .format() because it
// returns Arabic instead of English
var month = 1 + date.getMonth()
if (month < 10) {
month = '0' + month
}
var day = date.getDate()
if (day < 10) {
day = '0' + day
}
return date.getFullYear() + '-' + month + '-' + day
}
Answer in 2020 (Includes Timezone Support)
The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()
//** Returns now in ISO format in Central Time */
export function getNowISO() {
return `${moment().toISOString(true).substring(0, 23)}Z`
}
This will leave you with an exact ISO-formatted, localized string.
Important note: Moment now suggests using other packages for new projects.
If you need the formatting string : YYYY-MM-DDTHH:mm:ssZ
var date = moment();
console.log(date.format("YYYY-MM-DDTHH:mm:ssZ"));
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);

How to assume local time zone when parsing ISO 8601 date string?

I have a ISO date string as below
var startTimeISOString = "2013-03-10T02:00:00Z";
when I convert it to date object in javascript using below code, it returns
var startTimeDate = new Date(startTimeISOString);
output is
Date {Sun Mar 10 2013 07:30:00 GMT+0530 (India Standard Time)}
It sure converts the ISOString to date but it converts to local time since new Date() is client dependent. How to just convert iso date time string to date and time but not to local date-time..?
Thanks
According to MDN:
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time
zone, but given an ISO format such as "2014-03-07" it will assume a
time zone of UTC. Therefore Date objects produced using those strings
will represent different moments in time unless the system is set with
a local time zone of UTC. This means that two date strings that appear
equivalent may result in two different values depending on the format
of the string that is being converted (this behavior is changed in
ECMAScript ed 6 so that both will be treated as local).
I have done like this and am now getting the exact time which is inside the ISO date string instead of the local time
var startTimeISOString = "2013-03-10T02:00:00Z";
var startTime = new Date(startTimeISOString );
startTime = new Date( startTime.getTime() + ( startTime.getTimezoneOffset() * 60000 ) );
This will give the same date time inside iso date string , the output here is
o/p
Date {Sun Mar 10 2013 02:00:00 GMT+0530 (India Standard Time)}
To sum up the conversation from tracevipin's post:
All Date objects are based on a time value that is milliseconds since 1970-01-01T00:00:00Z so they are UTC at their core. This is different to UNIX, which uses a value that is represents seconds since the same epoch.
The Date.prototype.toString method returns an implementation dependent string that represents the time based on the system settings and timezone offset of the client (aka local time).
If a UTC ISO8601 time string is required, the Date.prototype.toISOString method can be used. It's quite easy to write a "shim" for this methods if required.
Lastly, do not trust Date.parse to parse a string. Support for an ISO8601 format UTC string is specified in ES5, however it's not consistently implemented across browsers in use. It is much better to parse the string manually (it's not hard, there are examples on SO of how to do it) if wide browser support is required (e.g. typical web application).
Simple ISO8601 UTC time stamp parser:
function dateObjectFromUTC(s) {
s = s.split(/\D/);
return new Date(Date.UTC(+s[0], --s[1], +s[2], +s[3], +s[4], +s[5], 0));
}
and here's a shim for toISOString:
if (typeof Date.prototype.toISOString != 'function') {
Date.prototype.toISOString = (function() {
function z(n){return (n<10? '0' : '') + n;}
function p(n){
n = n < 10? z(n) : n;
return n < 100? z(n) : n;
}
return function() {
return this.getUTCFullYear() + '-' +
z(this.getUTCMonth() + 1) + '-' +
z(this.getUTCDate()) + 'T' +
z(this.getUTCHours()) + ':' +
z(this.getUTCMinutes()) + ':' +
z(this.getUTCSeconds()) + '.' +
p(this.getUTCMilliseconds()) + 'Z';
}
}());
}
This happens because date is printed using toString method which by default returns the date and time in local timezone. The method toUTCString will give you the string you need.
Date actually keeps the date as unix time in milliseconds and provides methods to manipulate it.
In vanilla javascript there isn't a way to create a date that assumes the local time of the ISO formatted string you give it. Here's what happens when you pass an ISO 8601 formatted string to javascript. I'm going to use a non UTC time as it illustrates the problem better than using an ISO formatted string:
var startTime = new Date("2013-03-10T02:00:00+06:00"). Note this could also be 2013-03-10T02:00:00Z or any other ISO-formatted string.
read the time, apply the offset and calculate milliseconds since 1970-01-01T00:00:00Z
You now have only milliseconds - you have lost all timezone info. In this case 1362859200000
All functions, apart from the ones that give you a UTC representation of that number, will use the timezone of the computer running the code to interpret that number as a time.
To do what the original poster wants, you need to.
parse the ISO string, interpret the offset ('Z' or '+06:00') as the timezone offset
store the timezone offset
calculate and store the ms since epoch, using the offset timezone offset
hold that offset
whenever attempting to make a calculation or print the date, apply the timezone offset.
This isn't trivial, and requires a complete interpretation of the 8601 spec. Way too much code to put here.
This is exactly what moment.js is designed to do. I strongly recommend using it. Using moment.js:
moment("2013-03-10T02:00:00Z").format()
"2013-03-10T02:00:00Z"
this will result in printing the ISO time of the original string, preserving the offset.
you can try moment js library https://momentjs.com
For my case, I had 2022-10-17T01:00:00 on my database. SO I need to format it to the 01:00:00 AM.
So here was my solution.
var date = "2022-10-17T01:00:00"
var timeFormat = moment(date ).format('HH:mm A');
output: 01:00:00 AM
it will return ISOdate
var getDate = () => {
var dt = new Date();
var off = dt.getTimezoneOffset() * 60000
var newdt = new Date(dt - off).toISOString()
return newdt.slice(0, 19)
}
Output

Categories