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'
Related
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'
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?
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
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work
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?