time components if UTC and time zone is known - javascript

I have a date time picker, which uses getHours, getMinutes,.. to initialize the value. It works well if timezone coincide with user location, but I want to consider the case where user tz is different than the current browser locale setting. I can use Intl.DateTimeFormat to correctly format the date into another timezone. But, I want to get the time component values (hour, minute,..) of say "America/Chicago" while my local time is "America/New_York". That is I need to get time as 17 if I set offset as "America/Chicago", irrespective of current local timezone . Is this possible without using moment.js, or any better way to do this.
https://jsfiddle.net/zhvx6mmt/1/
const baseUTCDate = new Date(Date.UTC(2017, 2, 1, 23, 0, 0));
function formatDate(date, timeZone, locale) {
const options = { weekday: 'long', year: 'numeric', month: 'short',
day: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'short' };
return new Intl.DateTimeFormat(locale, Object.assign(options, {timeZone: timeZone})).format(date);
}
console.log(formatDate(baseUTCDate, "America/New_York", 'en-US'))
// Wednesday, Mar 1, 2017, 6:00 PM EST
console.log(formatDate(baseUTCDate, "America/Chicago", 'en-US'))
// Wednesday, Mar 1, 2017, 5:00 PM CST
console.log(baseUTCDate.getHours()) // 18 - local time zone is EST

Related

get new Date() in other timezone in full text string format

I need to get Thailand timezone in this format: Thu Nov 10 2022 14:08:37 GMT+0800 (Malaysia Time). I have tried new Date().toLocaleString("en-US", {timeZone: "Asia/Bangkok"}) but didn't get the correct format I want, probably because of the .toLocaleString(). Is there a simple way to do it?
As deceze suggests, you can use Intl.DateTimeFormat with suitable options to get the values you want. Then you can use formatToParts to reorganise them as you wish, e.g. to replicate the format of Date.prototype.toString for any timezone, you can use:
// Return timestamp in same format as Date.prototype.toString
// in designated timezone (IANA representative location)
function toTimezone(tz, date = new Date()) {
// Get parts except timezone name
let opts = {
year: 'numeric',
month: 'short',
day: '2-digit',
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: tz,
timeZoneName: 'shortOffset',
hour12: false
}
// To get full timezone name
let opts2 = {
hour: 'numeric',
timeZone: tz,
timeZoneName: 'long'
}
let toParts = opts => new Intl.DateTimeFormat('en', opts)
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
let {year, month, day, weekday, hour, minute,
second, timeZoneName} = toParts(opts);
// Fix offset
let sign = /\+/.test(timeZoneName)? '+' : '-';
let [oH, oM] = timeZoneName.substr(4).split(':');
let offset = `GMT${sign}${oH.padStart(2, '0')}${oM || '00'}`;
// Get timezone name
timeZoneName = toParts(opts2).timeZoneName;
return `${weekday} ${month} ${day} ${year} ${hour}:${minute}:${second} ${offset} (${timeZoneName})`;
}
// Examples
['Australia/Adelaide',
'Asia/Bangkok',
'Asia/Kolkata',
'America/New_York',
'Pacific/Yap',
'Pacific/Pago_Pago'
].forEach(tz => console.log(toTimezone(tz)));
Support for some options like shortOffset may not be ubiquitous yet. A formatting library with timezone support is a simpler (and more reliable) option. :-)
You can configure the locale string formatter with a whole bunch of options:
console.log(new Date().toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
}));
However, the exact format it will output will always be dependent on the locale used and the browser's understanding of how dates should be formatted for that locale. If you want more control over the exact formatting, you'll need to cobble it together yourself:
const date = new Date();
const time = date.toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
});
const weekday = date.toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
weekday: 'short'
});
console.log(`${weekday} ${date.getFullYear()} ... ${time}`);
If that seems too complicated, use some 3rd party library like Luxon, which can simplify that a bit.

Date.toLocaleString inadequacy for conversion of a date/time to universal time

I'm trying to convert a date object to UTC. Either I'm using it wrong or the Date.toLocaleString seems to be broken or inadequate.
new Date('Tue Aug 09 2022 18:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-US', {
timeZone: "UTC",
day: "2-digit",
hour12: false,
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
output:
"08/09/2022, 23:43:00" (A valid date/time)
new Date('Tue Aug 09 2022 19:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-US', {
timeZone: "UTC",
day: "2-digit",
hour12: false,
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
output:
"08/10/2022, 24:43:00"
I expected it to be "08/10/2022, 00:43:00" but instead it appears to not reset the hours.
I have worked around this, in the particular way I was using the result, but I would like to be able to go without the extra conditional and reset.
var parts = str.match(/(\d{2})\/(\d{2})\/(\d{4}),\s(\d{2})\:(\d{2})\:(\d{2})/),
month = parseInt(parts[1], 10),
day = parseInt(parts[2], 10),
year = parseInt(parts[3], 10),
hours = parseInt(parts[4], 10),
minutes = parseInt(parts[5], 10),
seconds = parseInt(parts[6], 10);
if (hours == 24) {
hours = 0;
}
Why is this happening, and how can I accomplish my goal?
Use hourCycle: "h23" instead of hour12: false in your options. Read more about the options on MDN.
console.log(
new Date('Tue Aug 09 2022 19:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-US', {
timeZone: "UTC",
day: "2-digit",
hourCycle: "h23",
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
);
.as-console-wrapper { max-height: 100% !important; height: 100%; }
I suppose it's the americain way of displaying time after midnight when using 24-hour (non 12 hour) time. Try using en-UK for locale:
console.log(
new Date('Tue Aug 09 2022 19:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-UK', {
timeZone: "UTC",
day: "2-digit",
hour12: false,
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
);

cs-Cz locale and JavaScript new Date Constructor doesn't allow for shorthand date

So I'm trying to follow the docs here on MDN regarding the date options for formatting
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
For the cs-cz locale, I want the month to be in "short" hand form when writing a date such as
19. 12. 2012 instead of 19. pro 201
This code works for locales such as en-us or it-it (italy) and others.
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
var options = { month: 'short', day: 'numeric', year: 'numeric'};
console.log(new Intl.DateTimeFormat('en-us', options).format(date));
Prints out Dec 19, 2012
Can anyone help me with getting the cs-cz locale to work. This code
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
var options = { month: 'short', day: 'numeric', year: 'numeric'};
console.log(new Intl.DateTimeFormat('cs-cz', options).format(date));
prints out
19. 12. 2012 instead of 19. pro 201
I'd like 19. pro 201 using the JavaScript Date Function. This is all dynamic in my code based on 13 locales and czech is the only one giving me trouble.
A weird conundrum for sure. As it turns out, if you include the week format in the options object it provides the output you seek. So the code below simple uses that and then removes the week name from the string.
I did not modify the year, and will leave that up to you, but I do believe this solves your problem and answers your question.
const options = { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' };
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
const out = date.toLocaleDateString('cs-CZ', options).split(' ').splice(1).join(' ');
console.log(out);

Js Date - Unix Time Stamp wrong result

Hi I have generated a Unix Time Stamp with an online generator and I choose that Date:
01/12/2020 # 9:30pm (UTC)
Which gave me result: 1578864600
I want to display it now in my react app: (date is my result above)
const timestamp = new Date().setMilliseconds(date);
const formattedDate = new Intl.DateTimeFormat('pl-PL', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
weekday: 'long',
hour: 'numeric',
minute: 'numeric',
}).format(timestamp);
But in my react app I am getting that wrong Date:
Tuesday, 14.01.2020, 17:07
Why it is calculating it wrong??

Date.toString(): How to prevent timezone name output in the PC locale in Chromium

In our logs we are using Date.toString() to store events timestamps.
Example:
Wed Nov 21 2018 02:04:38 GMT-0800 (Pacific Standard Time)
It is working well for us except when user's machine is in a locale other than English, then it would output timezone name in a local language (for example, Russian, Hebrew or Portugese)
Thu Nov 29 2018 16:21:07 GMT-0200 (Horário brasileiro de verão)
Is there a way to force toString() output to "EN-US" locale?
You can do it that way:
var options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: 'numeric', second: 'numeric', timeZoneName: 'short' };
new Date().toLocaleDateString("en-US", options)
Output:
"Fri, Dec 14, 2018, 3:17:54 PM EST"

Categories

Resources