TimeZone Information Not Formatted Correctly - javascript

I'm trying to format time to the user's timezone information. I'm using date-fns and date-fns-tz libraries to do that. Below is the code and output:
const utcToZonedTime = require('date-fns-tz/utcToZonedTime')
const formatDate = require('date-fns-tz/format')
const enGB = require('date-fns/locale/en-GB')
//tz is set to America/Los_Angeles
let tempDT = utcToZonedTime(new Date(classStartTime), tz)
tempDT = formatDate(tempDT, 'dd-MMM HH:mm a zzz', { timeZone: tz, locale: enGB})
console.log('tempDT', tempDT)
//This prints 13-Aug 07:30 AM GMT-7
What I need is 13-Aug 07:30 AM PST. When I use zzzz as timezone formatter, it does print the full name of timezone. But, short name is not working. What am I doing wrong?

Related

Angular date conversion UTC to EST

I have been trying to convert this time into EST "date": "2020-04-27T14:44:42Z". I am using angular and can get it into this format myFormat: 'MMM-DD-YYYY h:mm A' but can't seem to adjust the time to reflect est. Any help would be greatly appreciated.
Using momentjs
moment timezone makes is easy and convenient to convert+format. Command for npm install moment-timezone (this solution supports DST neutral TZ string 'America/New_York' instead of EST/EDT)
npm install --save moment moment-timezone
Code
import * as moment from 'moment-timezone';
// ...
// ...
const dateFormattedInEST = moment("2020-04-27T14:44:42Z").tz('America/New_York').format('MMM-DD-YYYY h:mm A');
Output: Apr-27-2020 10:44 AM
Moment gives lot of formatting options. Documentation https://momentjs.com/docs/#/displaying/format/
Using Angular pipes
Can be done using angular pipes as well (as pointed out by JSON Derulo).
Note: the format string are different from momentjs
{{"2020-04-27T14:44:42Z" | date : 'MMM-dd-YYYY h:mm a' : 'EDT'}}
Output: Apr-27-2020 10:44 AM
If you want to get hold off string for any other manipulation
import { DatePipe } from '#angular/common';
// ...
// ...
const dataAsStr = datePipe.transform("2020-04-27T14:44:42Z", 'MMM-dd-YYYY h:mm a', 'EDT');
Output: Apr-27-2020 10:44 AM
Here is some solution that I am applying now. You can use the method toLocaleString to do this.
Example 1:
const convertUTCDateToLocalDate = date => {
const newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
const offset = date.getTimezoneOffset() / 60;
const hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
const _date = convertUTCDateToLocalDate(new Date("2020-04-27T14:44:42Z"));
_date.toLocaleString(); // "4/28/2020, 6:44:42 AM"
Example 2:
const _date = new Date("2020-04-27T14:44:42Z");
const _est_date = _date.toLocaleString("en-US", {timeZone: "America/New_York"}); // "4/27/2020, 10:44:42 AM"
Just change the locale based on the requirement from your project.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Parse the datetime string and convert it to UTC using js-joda/core and js-joda/timezone

We have to build a website for our client that runs Angular 9+ in the front end and nodejs is the server backend application. Everything working good.
Now, my client wants to support customers initially from the following timezones: Indian Time, Pacific Time, Arizona Time, Mountain Time, Central Time and Eastern Time. We are planning to use #js-joda/core and #js-joda/timezone to accomplish the job.
One of the requirements is to validate the date entered by the user. The date must belong to the current month only. The server is set with UTC timezone. We are thinking about converting the datetime to UTC and then storing it in the (mongodb) database. But we are not sure how we can convert the given date to UTC using js-Joda. We tried using the following code but it doesn't seem to convert.
var jsJoda = require("#js-joda/core");
require("#js-joda/timezone");
var indiaZone = jsJoda.ZoneId.of("Asia/Calcutta");
var localDateTime = jsJoda.LocalDateTime.parse("2021-10-05T23:18:09.905");**//<--user entry date**
var localTime = jsJoda.ZonedDateTime.of(localDateTime, indiaZone);
var utcZoned = jsJoda.ZonedDateTime.of(localTime, jsJoda.ZoneOffset.UTC);
console.log('Current Time in UTC: ' + utcZoned.toString());
I expected the date printed would be 5.5 hrs behind but it didn't. Can you please assist if I'm in the right direction and also why the UTC time is showing the same time passed?
You can use ZonedDateTime#withZoneSameInstant to meet the requirement.
Demo:
import {
LocalDateTime,
ZoneId,
ZonedDateTime
} from "#js-joda/core";
import "#js-joda/timezone"; // Automatically adds timezone support
const zoneIdIndia = ZoneId.of("Asia/Kolkata");
const zoneIdUtc = ZoneId.of("Etc/UTC");
const ldt = LocalDateTime.parse("2021-10-05T23:18:09.905");
const zdtIndia = ldt.atZone(zoneIdIndia);
const zdtUtc = zdtIndia.withZoneSameInstant(zoneIdUtc);
console.log(zdtIndia.toString());
console.log(zdtUtc.toString());
Output:
2021-10-05T23:18:09.905+05:30[Asia/Kolkata]
2021-10-05T17:48:09.905Z[Etc/UTC]
My issue was that I had a string in eastern standard time that I needed to be converted to UTC using jsJoda.
Solution:
date: 2021-05-21
hour: 22
minute: 00
const jsJoda = require("#js-joda/core");
require('#js-joda/timezone');
let startTime = jsJoda.LocalDateTime.parse(`${date}T${hour}:${minute}`)
.atZone(jsJoda.ZoneId.of("America/New_York"))
.withZoneSameInstant(jshourJoda.ZoneId.of("UTC-00:00"));
_date: LocalDate { _year: 2021, _month: 5, _day: 22 },
_time: LocalTime { _hour: 2, _minute: 0, _second: 0, _nano: 0 }

Convert datetime with time zone to specific format with it's timzone

Convert
2020-11-15T02:20:00+03:00
To
15-11-2020 2:20 (+3:00) (any format will do, as long the showing the timezone)
moment or pure javascript (strictly no jquery)
Update:
+3:00 is dynamic value. Could be +4:00 or +5:00.
If your date format has a fixed timezone offset, try to use moment.parseZone.
const dateString = '2020-11-15T02:20:00+03:00';
const momentDate = moment.parseZone(dateString);
console.log(momentDate.format('DD-MM-YYYY h:mm (Z)'));
// Output: "15-11-2020 2:20 (+03:00)"
Update:
Use H instead of h:
const momentDate = moment.parseZone('2020-11-15T23:23:00+03:00');
console.log(momentDate.format('DD-MM-YYYY h:mm (Z)'));
// Wrong hour: "15-11-2020 11:23 (+03:00)"
console.log(momentDate.format('DD-MM-YYYY H:mm (Z)'));
// Correct output: "15-11-2020 23:23 (+03:00)"
Thanks to #MattJohnson-Pint for correcting the format template.
Demo - https://codepen.io/vyspiansky/pen/OJNRbPN

Get timestamp from date string without timezone and timezone name apart

I have a dateTime string in this (bad, I know) format coming from an external API:
const startDate = '2/13/2020 15:00';
and the timezone name:
const timezoneName = 'America/New_York';
Which means that the dateTime is 2/13/2020 15:00 in New York.
Any idea for an elegant way to get timestamp (or JavaScript date object)?
I don't mind using moment.js or/and moment-timezone if it helps.
Moment and Moment-Timezone are for legacy code.
For new applications, the Moment team recommends Luxon.
const startDate = '2/13/2020 15:00';
const timezoneName = 'America/New_York';
const dateTime = luxon.DateTime.fromFormat(startDate, 'M/d/yyyy HH:mm',
{ zone: timezoneName });
const utcDateTime = dateTime.toUTC();
const s = utcDateTime.toISO();
console.log(s); //=> "2020-02-13T20:00:00.000Z"
Using moment-timezone should work:
const moment = require('moment-timezone');
const t = moment.tz("2/13/2020 15:00", "MM/DD/YYYY HH:mm","America/New_York");
console.log(t.toISOString()); // Prints '2020-02-13T20:00:00.000Z'

Why is the value output by MomentJS not reflecting UTC time?

I am trying to get a particular day/time in UTC format. Example code
const today = moment().tz('America/New_York')
const tomorrow = today.add(1, 'days')
const formatTime = today.format('YYYY-MM-DD')
const time = '7:00 pm'
const deliveryTime = moment(`${formatTime} ${time}`)
console.log(deliveryTime.utc().format())
Shouldn't I be getting this as output 2019-10-01T19:00:00Z as I am getting it on https://repl.it/#azs06/SilkyBronzeInversion
Suppose to 2019-10-02T13:00:00Z this on https://jsfiddle.net/azs06/hkrvze1x/2/
Is this is because of Node.js implementation of date?
What would be proper way to convert date time to UTC using moment.js?

Categories

Resources