DayJS: Format and Convert an ISO Date/Time String to Local Timezone's Date/Time - javascript

I'm consuming an API which returns timestamps in this format 2023-02-18T14:54:28.555Z which is an ISO string. I need to format this value to the timezone of the user.
I've tried this:
dayjs("2023-02-18T14:54:28.555Z").format('YYYY-MM-DD HH:MM:ss A') // => "2023-02-18 20:02:28 PM"
The above output is incorrect and is 30 minutes behind for +0530 IST Timezone.
But when I input the same string "2023-02-18T14:54:28.555Z" to the JavaScript date constructor, I can see the correct value.
new Date("2023-02-18T14:54:28.555Z").toString() // => 'Sat Feb 18 2023 20:24:28 GMT+0530 (India Standard Time)'
How to get the correct formatted value for my Timezone using DayJS?
Tried feeding the ISO string to the DayJS constructor and expected it'll parse it to the current timezone. But the output value is 30 minutes behind.

you can use toLocaleString() method:
const timestamp = "2023-02-18T14:54:28.555Z";
const date = new Date(timestamp);
const options = { timeZone: 'Asia/Kolkata' };
const formattedDate = date.toLocaleString('en-US', options);
console.log(formattedDate);

Date.toString() displays the Date according to the local time of the OS. If you need the time to display in a zone other than the local time of the OS, then you'll have to use the DayJS Timezone plugin.
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
const timestamp = '2023-02-18T14:54:28.555Z';
dayjs.extend(utc);
dayjs.extend(timezone);
// Seattle time because my OS is set to America/Los_Angeles time.
const seattleString = Date(timestamp).toString();
const dayjsLocal = dayjs(timestamp);
const dayjsIst = dayjsLocal.tz('Asia/Calcutta');
const istString = dayjsIst.format('YYYY-MM-DDTHH:mm:ss');
console.log(seattleString); // Sun Feb 19 2023 02:43:42 GMT-0800 (Pacific Standard Time)
console.log(istString); // 2023-02-18T20:24:28

Related

Moment TZ - Convert date into another timezone ISO string

I'm trying to convert a date in GMT to PST. The GMT date is 2022-11-16T00:00:00, therefore the PST date should be 2022-11-15T16:00:00.
My code is as follows:
const startDateGMT = moment(startTime).tz(myTimezone, true);
console.log('START DATE GMT IS', startDateGMT, startDateGMT.toISOString());
This outputs 8AM on the 16th, instead of 4PM on the 15th:
START DATE GMT IS Moment<2022-11-16T00:00:00-08:00> 2022-11-16T08:00:00.000Z
What am I doing wrong?
You can use the moment.tz constructor to parse the input time, using the timezone Etc/GMT as the timezone.
You can then call .tz() on the resulting date to convert to Pacific time.
The example below creates the dates and formats them along with the relevant UTC offset.
const gmtTime = '2022-11-16T00:00:00';
const gmtDate = moment.tz(gmtTime, 'Etc/GMT');
const pstDate = moment.tz(gmtTime, 'Etc/GMT').tz('US/Pacific');
console.log('GMT Date:', gmtDate.format('YYYY-MM-DD HH:mm:ssZ'))
console.log('PST Date:', pstDate.format('YYYY-MM-DD HH:mm:ssZ'))
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

How to change ISO date to Standard JS Date?

I am trying to change an ISO date to a Standard JS Date format. The JS format I am referring to is:
Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)`
What is the best way to go about doing this? Thanks!
const ISO_DATE = '2020-07-14T23:02:27.713Z';
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toString();
};
console.log(formatDate(ISO_DATE));
One way is:
let isoDate = "2020-07-20T14:29:52Z";
var myDate = new Date(isoDate);
console.log(myDate.toString()); // Mon Jul 20 2020 17:29:52 GMT+0300 ( (your time zone)
console.log("Back to ISO Date: ", myDate .toISOString());
If you want to convert it back to ISO Date use:
console.log(myDate.toISOString());

Get Timezone Abbreviation from String

How would I get the time and abbreviated timezone from a String. What I am doing incorrectly?
const timestampString = 'Wed Dec 05 2018 22:00:00 GMT-0800 (Pacific Standard Time)';
const timezoneAbbreviation = moment.tz(timestampString).format('z'); // expecting PST, but result is UTC
That functionality was deprecated in moment and only available via moment-timezone like this:
const timestampString = 'Wed Dec 05 2018 22:00:00 GMT-0800 (Pacific Standard Time)';
const result = moment(new Date(timestampString)).tz('America/Los_Angeles').format('z')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
Note: that you need to instantiate moment with valid date first etc.
The reasoning behind this is that there was no consistent way to get that time zone abbreviation just from the native Date object toString as you can read here.
For anyone who is using date-fns-tz, you can find timezone abbreviation as following
const { utcToZonedTime, format } = require('date-fns-tz')
const date = new Date('2018-09-01T16:01:36.386Z')
const zonedDate = utcToZonedTime(date, 'America/Toronto')
const pattern = 'zzz'
const timeZoneAbbr = format(zonedDate, pattern, { timeZone: 'America/Toronto' })
-> timeZoneAbbr : EDT
Above is an example given in the documentation page

Convert Javascript date to UTC with timezone information

I have a UI that allows a user to create an event. When the user creates this event they select a date( and time) and separately they select a timezone (eg. 'America/New_York') for the event location.
I need to use the date (includes time) and the selected timezone (string) to create a UTC date. I'm not sure how to do this.
I thought about using getTimezoneOffset but doesn't this change depending on the time of year ( British Summer Time etc).
Update. I wasn't very clear in my explanation, so here is more detail:
User selects date and time of an event that is 'Jan 01 2017 07:00:00'.
They then select the timeZone of 'America/New_York'. It's happening at 7am in New York but I'm in the UK.
When I do:
const formatDate = moment.tz( new Date('Jan 01 2017 07:00:00'), 'America/New_York' ).format(); //returns '2017-01-01T02:00:00-05:00'
if I convert this date in new york to my local date with:
new Date( formatDate ); // returns 'Sun Jan 01 2017 07:00:00 GMT+0000 (GMT)'
I want it to return a local date and time of 'Sun Jan 01 2017 12:00:00 GMT+0000 (GMT)'.
From docs:
If you want an actual time zone -- time in a particular location, like
America/Los_Angeles, consider moment-timezone.
This suggests the feature is not built-in into Moment.js itself but the other library should get it done:
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
Beware that you should still store the named time zone in another column, because there's no way to deduct it from the date stored in MySQL.
I did it in the end with the following:
const momentTimezone = require( 'moment-timezone' );
const DateWithOffset = require( 'date-with-offset' );
module.exports = function( date, timezone ) {
const offset = momentTimezone.tz.zone( timezone ).offset( date );
const newDate = new DateWithOffset( date.toUTCString(), ( 0 - offset ) );
return newDate.toISOString();
};
There may be a better way of doing this, but this seems to work. I used the npm module date-with-offset which did the job required.

Convert date string into another string format

I have the date in this format:
Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time)
I want this string to be converted into this format:
2016-11-15 00:00:00
I tried:
var s = startDate.format('YYYY-MM-DD HH:mm:ss');
I would recommend using the library moment.js. This library was specifically designed to help with dates and formatting.
You simply need to do this:
let date = moment('Tue Nov 15 2016 00:00:00 GMT+0800').format('YYYY-MM-DD HH:mm:ss')
console.log(date)
However, there is a caveat. Since the date that you are providing is in a nonstandard format, you will get a deprecation warning, like this:
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Basically, the solution is to provide a standard format for your date. The simplest way to do that is to either chop off the timezone, since it seems like you will be displaying the date assuming the TZ supplied is the local one.
You can get it done just using vanilla javascript:
const date = new Date('Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time');
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const timeToHHMMSS = (hours, minutes, seconds) => {
return [hours, minutes, seconds].map(value => {
return ('0' + value).slice(-2);
}).join(':');
}
const formattedDate = `${year}-${month}-${day}`;
const formattedTime = timeToHHMMSS(hours, minutes, seconds);
console.log(`${formattedDate} ${formattedTime}`);

Categories

Resources