It will be very helpful to know if there is a way to format Date based on Timezone.
Ex:we give America/Los_Angeles as timezone,the output date should be formatted as MM-DD-YYYY.If we give timezone as Asia/Kolkata, It should be changed to DD-MM-YYYY.
I wanted to know if any library have any OOB method to auto format Date based on selected Timezone.
I have already tried using Locale support.Using Locale (en-US,en-GB,ja) we can format the date but none of the libraries stores which timezone uses which locale. We can use the browser locale(navigator.language) But This will not give desired output on locale and timezone mismatch.
Ex:
new Date(value).toLocaleString('en-US',{timeZone: "Asia/kolkata"}) // gives o/p in MM-DD-YYYY format.
ideally this should give O/P in DD-MM-YYYY format.
most of the libraries gives an OOB method to format the date but it expects an input string.
Ex: DateTime.fromFormat('May 25, 1982', 'MMMM dd, yyyy')
formatInTimeZone(date, 'America/New_York', 'yyyy-MM-dd HH:mm:ssXXX')
dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]')
i have checked below libraries:
https://www.npmjs.com/package/luxon
https://www.npmjs.com/package/dayjs
https://www.npmjs.com/package/date-fns-tz
I am looking for any help would be greatly appreciated. Thanks!!
2
Answers
You can simply use Intl.DateTimeFormat API. Here is how:
You can specify more options for formatting. Look at the documantation.
First: the timeZone "India/kolkata" is not valid.
I have pointed you to my es-date-fiddler library in a comment to your question, you answered it was not useful.
I’m not sure what you want to achieve, but as far as I know it is not possible to infer locale values from a timeZone value. Working with ES Dates, when no locale is given, the locale of the user is used. The locale (either specified or the users’ locale) determines the formatting for
toLocaleString([locale(s)])
. In other words:locale
is not related totimeZone
.Let’s give an example using the aforementioned library for the current date, locale
en-IN
(India) and timeZoneAsia/Kolkata
. Maybe it helps …See also the library’s demo for a bunch of examples.