I have a date format is GMT or UTC.
var mydate = '2020-01-14T17:43:37.000Z'
I want to convert this date in IST format so according to this date the output I need in this format.
var date = '2020-Jan-15 12:45'
I have a date format is GMT or UTC.
var mydate = '2020-01-14T17:43:37.000Z'
I want to convert this date in IST format so according to this date the output I need in this format.
var date = '2020-Jan-15 12:45'
You can specify an IANA time zone identifier in the options passed to toLocaleString
. The identifier for India is Asia/Kolkata
.
var s = new Date('2020-01-14T17:43:37.000Z').toLocaleString(undefined, {timeZone: 'Asia/Kolkata'});
This will do the correct time zone conversion, as the input is in UTC (as specified by the Z
at the end).
undefined
means to use the user's locale for the formatting of the date and time. This is usually what you want. If you want a more particular format (like what you specified in your question), you can provide a specific locale string and/or adjust the other options for toLocaleString
, as given in the docs.
Also, note that the conversion in your question is incorrect. India is 5 hours an 30 minutes offset from UTC. Thus the correct output is 2020-01-14 23:13:37
(in whatever format you like)
Another option for you is to use the moment and moment timezone modules for timezone conversion, they are very flexible and you can format the resulting date object according to whichever format you wish.
As mentioned by @matt-johnson-pint (thank you!) you can also use the very cool Luxon library for this purpose, I've added an example below.
const mydate = "2020-01-14T17:43:37.000Z"
// Create a UTC date object. The moment constructor will recognize the date as UTC since it includes the 'Z' timezone specifier.
let utcDate = moment(mydate);
// Convert the UTC date into IST
let istDate = moment(mydate).tz("Asia/Kolkata");
console.log("Using Moment.js:");
console.log(`UTC date (iso): ${utcDate.format("YYYY-MM-DD HH:mm:ss")}`);
console.log(`IST date (iso): ${istDate.format("YYYY-MM-DD HH:mm:ss")}`);
const DateTime = luxon.DateTime;
utcDate = DateTime.fromISO(mydate);
istDate = DateTime.fromISO(mydate).setZone("Asia/Kolkata");
console.log(`\nUsing Luxon:`);
console.log(`UTC date (iso): ${utcDate.toFormat("yyyy-LL-dd HH:mm:ss")}`);
console.log(`IST date (iso): ${istDate.toFormat("yyyy-LL-dd HH:mm:ss")}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
© 2022 - 2024 — McMap. All rights reserved.