-3

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);
Dipu
  • 45
  • 1
  • 2
  • 16

2 Answers2

6

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

-3

You can use moment if you have a moment .

momenttime = moment()
momenttime.format("YYYY-MM-DD hh:mm:ss ")
azyth
  • 698
  • 5
  • 19