I have a UTC time with offset like below. I'm trying to format the UTC date time string using format function from date-fns library.
import { format } from "date-fns";
const utcDateTime = "2021-10-14T21:03:56.3256046+00:00";
const formattedDate = format(new Date(utcDateTime), "MM/dd/yyyy hh:mm");
What I'm expecting is 10/14/2021 21:03, a 24 hour time format but what I get is 10/14/2021 04:03, a converted date time for my timezone.
How to display the date and time exactly like with UTC time instead of converting the date time to local timezone?
I created a working example using CodeSandbox. Could anyone please help?
After spending a lot of time, I was able to achieve the desired result using the plain JavaScript Date object and its functions.
First, parsing the date time string and converting it to ISO string using toISOString() function.
Second, splitting the formatted date and time extracts from the ISO string.
Below is the code
const formatToUTCDateTime = (dateString) => {
const date = new Date(Date.parse(dateString));
const formattedDate = date.toISOString().split("T")[0].split("-");
const formattedTime = date.toISOString().split("T")[1].split(":");
return `${formattedDate[1]}/${formattedDate[2]}/${formattedDate[0]} ${formattedTime[0]}:${formattedTime[1]}`;
};
console.log("Result - ", formatToUTCDateTime("2021-10-14T20:03:56.3256046+00:00"));
Related
Hello I have a function which converts a local time to UTC using the local timezone and date:
this.conversion.dateTimeToTime('2022-07-04 12:30', 'America/Los_Angeles');
public dateTimeToTime(date, timezone = 'UTC') {
date = new Date(date);
return date.toLocaleTimeString('en-GB', {timeZone: timezone, hour12: false});
}
}
this is 12:30 local to UTC which should be 20:30(ish) but the output is 4:30utc instead going backwards
I am wondering what I am doing wrong
Thanks
Keeping date as simple date string(2022-01-31) causes data loss in JS and providing it to Date constructor can result in wrong date. Check this SO question for more.
Generally I convert my date to ISO format by using Date.toISOString. Next when I want to parse it as JS Date object, I use parseISO method of date-fns.
Here is a CodeSandbox example: https://codesandbox.io/s/summer-bush-iv0h2g?file=/src/index.js
I have used moment-tz instead:
import * as moment from "moment-timezone";
let blah = moment.tz("2019-06-03 12:30", "America/Los_Angeles");
console.log(blah.format());
console.log(blah.clone().tz("UTC").format());
I have the following date time 2012-05-01T00:00:00T+01:00
Is this a standard date time format? It seems to have a timezone in the end. So it doesnt seem to be either ISO 8601 or UTC ?
How do I output this in Javascript for todays date ?
There are several options for you
let inputFormat = "2012-05-01T00:00:00T+01:00"
let customDateFormat = new Date(sample.split("+")[0].split("T").join(" "))
OR best way => moment.js
let inputFormat = "2012-05-01T00:00:00T+01:00"
let customDateFormat = moment(sample.split("+")[0].split("T").join(" ")).format("DD/MM/YYYY")
Users are able to submit only the date part of a date stamp e.g. 2020-12-01, assuming that the time will be 00:00:00
So, if I have the above value, I want to update the time to its UTC value. So if I am in the EST timezone, I want to convert 2020-12-01 to 2020-12-01 05:00:00 to account for the five hour offset.
Can I do this with date-fns-tz?
const { zonedTimeToUtc, format } = require("date-fns-tz");
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
const utcDate = zonedTimeToUtc(new Date("2020-12-01"), tz);
document.getElementById("app").innerHTML = `${format(
utcDate,
"yyyy-MM-dd HH:mm:ss"
)}
`;
The above yields 2020-11-30 19:00:00, which is moving the time 5 hours in the wrong direction.
https://codesandbox.io/s/happy-hoover-dn417?file=/src/index.js:23-301
Given:
const utcDate = zonedTimeToUtc(new Date("2020-12-01"), tz);
The built–in parser will be used to parse the string, so it will be parsed as UTC, then date-fns will apply the offset for the tz. Don't do that, use:
const utcDate = zonedTimeToUtc("2020-12-01", tz);
so that date-fns parses the string using the tz. Now utcDate.toISOString() produces "2020-12-01T05:00:00.000Z", which is the equivalent UTC date and time where tz is America/New_York.
Date-fns seems to always use the host timezone offset for output, the timeZone option just changes the text offset, it doesn't modify the actual timestamp values. Likely you have to use utcToZonedTime first to adjust the Date. I struggle with date-fns, I find the documentation seriously lacking in useful examples.
I'd just use toISOString and remove the "T" and "Z".
When I want to convert the Gregorian date to Persian date, it converts the value of the minute in the date conversion to error.
For example I want to convert this date time to Persian date:
2020-09-14T16:51:00+04:30 must convert to this 1399/06/24 16:51 but when convert date it show me this time 1399/06/24 00:06 it mistake to convert 16:51, show this: 00:06.
This is my code to convert date:
toPersianDate(date: any, format = 'YYYY/MM/DD HH:MM'): string {
let dateTime;
const MomentDate = moment(date, 'YYYY/MM/DD');
dateTime = MomentDate.locale('fa').format('jYYYY/jMM/jDD HH:jMM');
return dateTime;
}
What's the problem? How can I solve this problem?
the MM is used for month formatting, so it is trying to format the minutes into a month.
What you need to use is the small mm. Moreover, I don't this you need the j before the mm as the minutes are the same in Jalali time.
So what you actually need is this: MomentDate.locale('fa').format('jYYYY/jMM/jDD HH:mm');
You can read more about the formatting here.
I'm getting a date as a string, in the following format (for example):
"11/10/2015 10:00:00"
This is UTC time.
When I create Date from this string, it consider it as local time:
let time = "11/10/2015 10:00:00";
let date = new Date(time);
console.log(date);
it prints:
"Tue Nov 10 2015 10:00:00 GMT+0200"
(instead of considering it as UTC: "Tue Nov 10 2015 10:00:00")
I also tried moment.js for that.
is there a good way to make Date() consider the string a UTC, without adding "Z"/"UTC"/"+000" in the end of the string?
You can use the built-in Date.UTC() function to do this. Here's a little function that will take the format you gave in your original post and converts it to a UTC date string
let time = "11/10/2015 10:00:00";
function getUTCDate(dateString) {
// dateString format will be "MM/DD/YYYY HH:mm:ss"
var [date, time] = dateString.split(" ");
var [month, day, year] = date.split("/");
var [hours, minutes, seconds] = time.split(":");
// month is 0 indexed in Date operations, subtract 1 when converting string to Date object
return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)).toUTCString();
}
console.log(getUTCDate(time));
Your date is parsed by the date constructor, in MM/DD/YYYY format, applying the local timezone offset (so the output represents local midnight at the start of the day in question). If your date really is MM/DD/YYYY, all you need to do is subtract the timezone offset and you'll have the UTC date...
var myDate = new Date("11/10/2015 10:00:00");
myDate = new Date( myDate.getTime() - (myDate.getTimezoneOffset()*60*1000));
console.log(myDate.toLocaleString([],{timeZone:'UTC'}))
Here's everything I know about managing timezone when serializing and deserializing dates. All the timezone handling is static! JS dates have no intrinsic timezone.
You can use Date.UTC for this but you will have to parse your string and put every part of it as args by yourself as it can't parse such string. Also you could use moment.js to parse it: Convert date to another timezone in JavaScript
Also, seems like new Date("11/10/2015 10:00:00 GMT") parses date as a GMT and only after that converts it to PC local time
Easy answer is to append a "Z" at the end without changing the variable:
let time = "11/10/2015 10:00:00";
let date = new Date(time + "Z");
console.log(date);