Angular date conversion UTC to EST - javascript

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

Related

How to convert one time format to another in javascript using moment.tz?

I have tried various methods but I'm unable to convert date like 1640638800 to 2022-11-27 16:00:00 America/New_York timezone format in javascript using moment.tz.
My current code was like
import * as moment from 'moment';
var date= new Date(0);
date.setUTCSeconds(1640638800);
moment.tz(date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay() + " 10:00:00", "America/New_York");
import moment from 'moment-timezone'
// Unix Timestamp (milliseconds)
const ts = 1640638800 * 1000
// Parse as timezoned moment
const m = moment.tz(ts, "America/New_York")
// Format moment to string
const formatted = m.format('YYYY-MM-DD HH:mm:ss')
console.log(formatted) // '2021-12-27 16:00:00'

TimeZone Information Not Formatted Correctly

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?

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'

React native moment formatted date in invalid

I have the following code in my RN application.
getFormattedDate = (date) => {
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
return { date: formattedDate };
}
When I run this on the emulator, the formatted date is displayed properly. But when I run this on device, it says, invalid date. What am I doing wrong here?
From your comments, I assume that the date parameter is a string. If you want to create a new moment from a string, you have to pass the date format. The newly created moment can then be formatted with .format to get a string again.
Change:
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
To:
const formattedDate = moment(date,"MMM, DD YYYY").format("MMMM, DD YYYY");
Here you can find more details about the string format.
npm install date-fns --save
import { format } from 'date-fns'
format(new Date(), 'MMMM, DD YYYY')
Check this document
Moment is 150x slower than new Date . Please try it like this if you want to use this code working.
getFormattedDate = async (date) => {
const formattedDate = await moment(new Date(date)).format('MMMM,DD YYYY');
return { date: formattedDate };
}
you can read it here for more details
https://github.com/moment/moment/issues/731
I would suggest avoid using moment because of the performance.
Use new Date () and then fetch the day , month and year and change into suitable format by joining the strings as you want. Use only Date library.

Categories

Resources