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.

2

2 Answers

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

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

4

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:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like