marnusw / date-fns-tz Goto Github PK
View Code? Open in Web Editor NEWComplementary library for date-fns v2 adding IANA time zone support
License: MIT License
Complementary library for date-fns v2 adding IANA time zone support
License: MIT License
I have been struggling with an ISO 8601 date string that we need to display and perserve the offset (not display it in the users local time). Here is the input in ISO-8601 format-
Source
2020-01-09T20:00-05:00
Formatting
import { toDate, format } from 'date-fns-tz';
const dateWithTz = toDate('2020-01-09T20:00-05:00');
const formatted = format(dateWithTz, ' hh:mm a - eeee, MMMM d, yyyy');
result
06:00 PM - Thursday, January 9, 2020 // my local time
expected
08:00 PM - Thursday, January 9, 2020 // the correct time in the specified offset
Am I missing a step here?
new Intl.DateTimeFormat does not support different timezones in ie11. do you have any idea how to make it work in ie11?
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat)
timeZone
The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".
thanks a lot
cannot make it work, doesn't load
2020-03-**03** 11:00 PM GMT-7
(California)const { toDate, format } = require('date-fns-tz');
console.log(' UTC:', new Date().toUTCString());
console.log(' Local time:', new Date().toTimeString());
console.log('America/Sao_Paulo:', format(new Date(), 'yyyy-MM-dd HH:mm:ss zzz', { timeZone: 'America/Sao_Paulo' }));
Output:
$ date
Fri Apr 3 23:37:51 PDT 2020
$ node --version
v10.15.1
$ node .
UTC: Sat, 04 Apr 2020 06:37:59 GMT
Local time: 23:37:59 GMT-0700 (Pacific Daylight Time)
America/Sao_Paulo: 2020-04-03 23:37:59 GMT-3
"dependencies": {
"date-fns": "^2.11.1",
"date-fns-tz": "^1.0.10"
}
The utcToZonedTime
function adds an extra day if the timeZone
parameter is "UTC" and the time portion of the passed date value is between "00:00:00.000Z" and "00:59:59.999Z".
window.console.log(utcToZonedTime(new Date('2020-02-19T18:59:59.999-0500'), 'UTC')); // Wed Feb 19 2020 23:59:59 GMT-0500 (Eastern Standard Time)
window.console.log(utcToZonedTime(new Date('2020-02-19T19:00:00.000-0500'), 'UTC')); // Fri Feb 21 2020 00:00:00 GMT-0500 (Eastern Standard Time)
window.console.log(utcToZonedTime(new Date('2020-02-19T19:59:59.999-0500'), 'UTC')); // Fri Feb 21 2020 00:59:59 GMT-0500 (Eastern Standard Time)
window.console.log(utcToZonedTime(new Date('2020-02-19T20:00:00.000-0500'), 'UTC')); // Thu Feb 20 2020 01:00:00 GMT-0500 (Eastern Standard Time)
Using [email protected].
When I enter Europe/Berlin as timezone all browsers accepts this but of course Internet Explorer does not. I get the following error code:
Error in render: "RangeError: Option value 'EUROPE/BERLIN' for 'timeZone' is outside of valid range. Expected: ['UTC']"
From #38, which was prematurely closed by its author. Here I'm pasting and editing relevant parts from #38.
The issue appears to exist on Chrome versions 80 and above. Relevant Chrome bug report, which has been closed and marked as WON'T FIX: https://bugs.chromium.org/p/chromium/issues/detail?id=1045791
An example of the problem: https://codepen.io/atomcorp/pen/gObqoyX
In short the following returns a Date object for the 24th not 23rd:
utcToZonedTime(
new Date('Thu Jan 23 2020 05:00:00 GMT+0000 (Greenwich Mean Time)'),
'America/New_York' // -5 hours
);
It seems to happen when the inputted time matches the offset of the timezone. So if you move the time of the inputted date an hour back or forward, so it's different to the timezone offset, both utcToZonedTime and the native method return the same.
It's specifically related to do with Intl.DateTimeFormat which is used in tzTokenizeDate.
const dateTime = new Intl.DateTimeFormat('en-US', {
hour12: false,
timeZone: 'America/New_York',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
const date = dateTime.format(new Date(2020, 0, 25, 5, 0, 0));
// Chome 79/Firefox etc: date === 01/25/2020, 00:00:00
// Chrome 81: date === 01/25/2020, 24:00:00
Hi @marnusw,
thanks for your awesome project.
I'm working on a project that only uses es modules and therefore doesn't have a transformation step for other module formats. When I imported date-fns-tz I got an error that some modules don't export a default.
So I investigated and found out that the esm functions don't import from date-fns/esm
but from date-fns
directly (example: https://github.com/marnusw/date-fns-tz/blob/master/src/zonedTimeToUtc/index.js#L1).
I edited your build script to modify the paths. I hope I got that hole situation right?
Thanks for Awesome library!
While converting from string date to required timezone, is giving wrong time.
Date string is in UTC
utcToZonedTime('2019-03-20 10:51:43', 'America/New_York');
expected value is 03-20-2019 06:52
actual value is 03-20-2019 01:21
we were using moment before, as shown below, and it gives expected result
moment.utc(date).tz(timeZone)
Thanks!!
zonedTimeToUtc('2019-11-26T10:00:00', 'America/Chicago');
// returns correct 2019-11-26T16:00:00.000Z
zonedTimeToUtc('2019-11-26T10:00:00', 'Etc/GMT+6');
// returns incorrect 2019-11-26T10:00:000Z, timezone Etc/GMT+6 is silently ignored. Nor Unsupported time zone specified is thrown. It should return too 2019-11-26T16:00:00.000Z. It's Central Standard Time (CST).
Etc/GMT+6 is correct timezone identification by IANA database https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
findTimeZone('Etc/GMT+6')
from require('timezone-support')
confirming that timezone exists.
zonedTimeToUtc
is not working generally with timezones 'Etc/GMT+X'.
Versions:
date-fns-tz: v.1.0.8
date-fns: v.2.8.1
Using the latest version of date-fns:
format(zonedDate, 'yyyy-MM-dd HH:mm:ss zzz', { timeZone: 'Europe/Paris' })
// Expected output: 2014-10-25 06:46:20 CET
// Actual output: 2020-02-21 23:45:00 GMT+1
Yet when I used America/New_York
it was correct.
I was able to get something working with timezone-support
to get the timezone abbreviation value I wanted for now though.
Hello,
Here is my test code :
https://repl.it/@turutosiya/date-fns-tz-test
const { format, toDate } = require('date-fns-tz');
console.log(format(toDate('2019-08-27T15:00:00Z'), 'yyyy-MM-dd', {timeZone: 'Asia/Tokyo'}));
What I expected to get is 2019-08-28
, Since Asia/Tokyo
is in JST(+0900).
But in fact, I got 2019-08-27
.
Is this correct?
@marnusw While converting to a timezone the millisecond part was rounded over to 0.
Below code shows the output
console.log(
new Date(timestamp).toISOString(),
utcToZonedTime(timestamp, timezone).toISOString()
);
2019-09-30T22:01:59.117Z // actual time
2019-09-30T09:31:59.000Z // converted value.
Is millisecond precision supported by the library ?
Using [email protected]
Chrome 80.0.3987.132
System timezone is set to America/Los_Angeles
const date = new Date("1850-01-01T00:00:00") // Tue Jan 01 1850 00:00:00 GMT-0752
date.toISOString() // 1850-01-01T07:52:58.000Z
zonedTimeToUtc(
date,
"America/Los_Angeles"
).toISOString() // 1850-01-01T07:53:58.000Z
System timezone is set to America/New_York
const date = new Date("1850-01-01T00:00:00") // Tue Jan 01 1850 00:00:00 GMT-0456
date.toISOString() // 1850-01-01T04:56:02.000Z
zonedTimeToUtc(
date,
"America/New_York"
).toISOString() // 1850-01-01T04:57:02.000Z
Same thing happens in GMT-0344 (America/Miquelon
), GMT-0209 (America/Noronha
) and probably in other timezones that have such uncommon offsets
Upd:
For now, it seems like it is the issue with date-fns
's format
fn (which is used in zonedTimeToUtc
fn)
It behaves like this:
format(new Date("1850-01-01T00:00:00"), "HH:mm:ss") // 00:01:00
These are the proposed functions for date-fns-tz
version 2. Comments are welcome.
parseUTC
Parse a date string representing UTC time to a Date
instance. This is a reexport of date-fns/parseJSON
with a more semantically relevant name.
localToZonedTime
Transform a Date
instance in the local system time zone, i.e. when it is passed to format
it would show the local time, to a zoned Date
instance of the target time zone, i.e. when passed to format
it would show the equivalent time in that time zone.
This is achieved by modifying the underlying timestamp of the Date
. In other words, since a JS Date
can only ever be in the system time zone, the way to fake another time zone is to change the timestamp.
Matching the convention set by date-fns
this function does not accept string arguments. A date string should be parsed with parseUTC
, parseISO
or parse
first.
zonedToLocalTime
Transform a Date
instance representing the time in some time zone other than the local system time zone to a Date
instance with the equivalent value in the local system time zone, i.e. formatting the result or calling .toString()
will show the equivalent local time.
This is achieved by modifying the underlying timestamp of the Date
. It is the inverse of localToZonedTime
, so in this case it is assumed the input is faking another time zone, and the timestamp is changed to be correct in the current local time zone.
Matching the convention set by date-fns
this function does not accept string arguments. A date string should be parsed with parse
first.
utcToZonedTime
This is an alias of localToZonedTime
which can be used when it makes better semantic sense, such as when a UTC date received from an API is being parsed for display in a targed time zone. Since a UTC time will usually be provided as a string value, this function accepts UTC date strings that can be parsed by the parseUTC
function and does so internally.
zonedTimeToUTC
This is an alias of zonedToLocalTime
which can be used when it makes better semantic sense, such as when the intent is to save the UTC time of a date to an API. The resulting Date
which formats correctly in the system time zone has the desired internal UTC time, and thus the actual UTC value can be obtained from zonedTimeToUTC(...).toISOString()
or .getTime()
.
format
Full time zone formatting support, without any modification to the date instance. (No changes from format
in v1, except that it will no longer accept string inputs.)
formatAsZonedTime
A combination of utcToZonedTime
(or localToZonedTime
) and format
. In other words the date will be transformed to the target time zone specified in the options prior to formatting. Since utcToZonedTime
is used internally the date argument can also be a string that can be parsed by parseUTC
.
parseISO
As in date-fns
the previous implementation of toDate
in date-fns-tz@1
has been renamed to parseISO
. It extends the date-fns
version of this function with better time zone support. It is a rather large function, though, and should only be used when dates are not in ISO format or date strings represent a time zone other than UTC time. When this is not the case parseUTC
should be used instead.
i still confuse how to format 2019-10-16T10:10:54+08:00
to be 16-10-2019 10:10:54
in my local time(gmt+7)
i want to be formatted as is, not converted to my local, how to do that?
note: i dont want to include IANA Asia/Makassar
in formatting, i just want using that string only
Say we have the following code February the 8th 2019:
const { format } = require('date-fns-tz');
format(new Date(), 'DD');
The expected output is 08
The actual ouput is 51
I can't seem to be able to convert a unix time to UTC timezone:
const LOCAL_TIMEZONE='Europe/Oslo';
const TIMEZONE = 'UTC';
const value = 1582156800;
const d1 = fromUnixTime(value);
console.log(d1) //Thu Feb 20 2020 01:00:00 GMT+0100 (Central European Standard Time)
const d2 = zonedTimeToUtc(d1, LOCAL_TIMEZONE, {
timeZone: TIMEZONE,
});
console.log(d2) //Thu Feb 20 2020 01:00:00 GMT+0100 (Central European Standard Time)
Am I missing something? I tried from the examples and I get the same thing
After add to the project
These dependencies were not found:
* date-fns/_lib/cloneObject in ./node_modules/date-fns-tz/esm/zonedTimeToUtc/index.js
* date-fns/_lib/toInteger/index.js in ./node_modules/date-fns-tz/esm/toDate/index.js
* date-fns/subMilliseconds in ./node_modules/date-fns-tz/esm/utcToZonedTime/index.js
To install them, you can run: npm install --save date-fns/_lib/cloneObject date-fns/_lib/toInteger/index.js date-fns/subMilliseconds
I've been chasing down a bug where we're passing in poorly formatted timezones to date-fns-tz
and noticed that I can provide utcToZonedTime
with imaginary time zones and still get a result back
> utcToZonedTime(Date.now(), 'America/Chicago')
2019-06-12T22:33:56.000Z
> utcToZonedTime(Date.now(), 'America/Hello, date-fns-tz!')
2019-06-13T03:34:15.000Z
> utcToZonedTime(Date.now(), 'What is happening?')
2019-06-13T03:36:23.000Z
Is this behavior intentional?
Say we have the following code at February 2019:
const { format } = require('date-fns-tz');
format(new Date(), '[the] MM/YYYY');
The expected output is 02/2019
The actual ouput is [154963275526] 02/2019
As explained on the date-fns
documentation, the we should be able to escape a string in the date format with []
.
I want to report about an issue connected with date-fns-tz utcToZonedTime function. Whenever I pass time which is between 00:00 to 01:00 and give a timezoneId it formats with next day date. For example when I pass utcToZonedTime(1581398100000, 'America/New_York') (1581398100000 as utc string "Tue Feb 11 2020 05:15:00") the result is "Wed Feb 12 2020 00:15:00 GMT-0500 (Eastern Standard Time)" which is wrong it should be "Wed Feb 11 2020 00:15:00 GMT-0500 (Eastern Standard Time)". I found out that this is happening on chrome Version 80.0.3987.87 (64-bit)
Seeing an issuee when trying to use date-fns-tz
in a TypeScript project.
Library | Version |
---|---|
create-react-app | 2.1.1 |
date-fns | 2.0.0-alpha.26 |
date-fns-tz | 0.1.2 |
create-react-app <projectName> --typescript
App.tsx
and import date-fns
and date-fns-tz
, e.g:import { addMinutes } from "date-fns";
import { utcToZonedTime } from 'date-fns-tz'
npm start
/ yarn start
App runs
Compile error
[snip]node_modules/date-fns-tz/typings.d.ts
Type error: Duplicate identifier 'Options'. TS2300
27 | // Type Aliases
28 |
> 29 | type Options = {
| ^
30 | weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6
31 | firstWeekContainsDate?: 1 | 2 | 3 | 4 | 5 | 6 | 7
32 | additionalDigits?: 0 | 1 | 2
If I manually remove Options
, OptionsAliased
, Locale
, LocaleAliased
from node_modules/date-fns-tz/typings.d.ts
, then it compiles, and I think the functions from date-fns-tz
are still typed as expected?
When trying to call dateFnsTz.toDate("2019-11-20T22:59Z[Etc/UTC]")
we get an exception:
RangeError: Expected Area/Location(/Location)* for time zone, got Z[Etc/U
However, Etc/UTC
is a valid IANA zone
Using the example on line 26 of utcToZonedTime/index.js, I did this:
const result = utcToZonedTime('2014-06-25T10:00:00.000Z', 'America/New_York').toISOString()
;
I expected result
to equal 2014-06-25T06:00:00.000Z
, but it's actually 2014-06-25T09:00:00.000Z
. Why does that happen? Is it considering the first param to be in the local timezone rather than UTC? cause I'm in GMT-3 and NY is just 1 hour away(in June), hence my suspicion.
I'm on node 8.9.4, date-fns-tz 1.0.10.
I compiled the following code...
src/index.ts)
import {format as dateFormat} from 'date-fns-tz';
dateFormat(new Date(), 'YYYYMMdd', {timeZone: 'America/New_York'});
The following error occurred.
./node_modules/.bin/tsc --project tsconfigs.json
node_modules/date-fns-tz/typings.d.ts:34:31 - error TS2694: Namespace '"date-fns"' has no exported member 'Locale'.
34 locale?: import('date-fns').Locale
~~~~~~
Found 1 error.
package-lock.json)
{
"name": "reproduce-date-fns-tz-typing-bug",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"date-fns": {
"version": "2.0.0-alpha.13",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.0.0-alpha.13.tgz",
"integrity": "sha1-oP1yPEZ7XFupi8nX/hvu9eak1ZY="
},
"date-fns-tz": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-1.0.6.tgz",
"integrity": "sha512-g0IY9CebRuyB5e2GIueO9mHpySpauMxSkbdkmVQEWi/R3w49ikYxC3dBNruGSOegwiNLI9cjuM0POZOFX0r8zQ=="
},
"typescript": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-3.3.3.tgz",
"integrity": "sha512-Y21Xqe54TBVp+VDSNbuDYdGw0BpoR/Q6wo/+35M8PAU0vipahnyduJWirxxdxjsAkS7hue53x2zp8gz7F05u0A=="
}
}
}
tsconfigs.json)
{
"compilerOptions": {
"lib": [
"es2018"
],
"module": "commonjs",
"newLine": "LF",
"target": "es5",
"strict": true
},
"include": [
"./src"
]
}
console.log(new Date(2020, 3, 10, 11));
print: Fri Apr 10 2020 11:00:00 GMT-0300 (Brasilia Standard Time)
console.log(parseISO('2020-04-10T14:00:00.000Z'));
print: Fri Apr 10 2020 11:00:00 GMT-0300 (Brasilia Standard Time)
console.log(isEqual(new Date(2020, 3, 10, 11), parseISO('2020-04-11T14:00:00.000Z')));
print: false
format(new Date(), PPPP p zzz, { timeZone: 'Asia/Tokyo', locale: ja })
this should return 2019年12月4日水曜日 JST
however it returns 2019年12月4日水曜日 GMT+9
format
properly returns PST
or CST
if timeZone is America/Los_Angeles
or America/Chicago
.
Same thing seems to happen for timezones in europe as well.
Europe/Paris
returns GMT+1
rather than CET
Running "date-fns": "^2.8.1" and "date-fns-tz": "^1.0.8"
Hello, first of thanks for your work, dates are such a pain, I don't even want to think about working on a date library 😫
Anyway, I've come across this issue with date-fns-tz, I've tried to make a reduced issue here: https://codepen.io/atomcorp/pen/gObqoyX
In short the following returns a Date object for the 24th not 23rd
utcToZonedTime(
new Date('Thu Jan 23 2020 05:00:00 GMT+0000 (Greenwich Mean Time)'),
'America/New_York' // -5 hours
);
It seems to happen when the inputted time matches the offset of the timezone. So if you move the time of the inputted date an hour back or forward, so it's different to the timezone offset, both utcToZonedTime and the native method return the same.
Like I said times are weird, so maybe this is expected behaviour!? 🤷♂️
Hi!
I'm using react-native-localize
on my app to get user timezone. Out of it I got US/Pacific
when then passing to my backend and handling this timezone with date-fns-tz
I got Invalid time zone specified: US/Pacific
.
I believe this timezone comes from a simulator device because the app is in review on the Apple store. Not sure if it's the reason and the timezone is falsy for a reason.
For this example have browser TZ in "America/Chicago"
Start with:
start: 2019-11-03 01:00:00 [-10:00] HST | 1572760800000
Add 1 hour:
plusHour: 2019-11-03 01:00:00 [-10:00] HST | 1572764400000
Check start again for mutability:
start: 2019-11-03 01:00:00 [-10:00] HST | 1572760800000
Difference in hours: (should be 1)
dH: 1
Convert both to UTC:
(e.g. zonedTimeToUtc(start, "Pacific/Honolulu")
startUtc: 2019-11-03 05:00:00 [+00:00] UTC | 1572778800000
plusHourUtc: 2019-11-03 05:00:00 [+00:00] UTC | 1572778800000
Difference in hours: (should be 1)
dHUtc: 0
basically the zonedTimeToUtc of a valid timestamp that is equivalent to an invalid timestamp doesn't work
I was wondering if this lib takes care of Summertime/wintertime.
If so it probably only works with IANA and not with the offsets, right?
I'm getting unexpected output when using format
method.
this is valid for v2.10
consider this example:
import format from "date-fns-tz/format";
import parseISO from "date-fns/paseISO";
function getTimeString(dateInput: string): string {
return format(parseISO(dateInput), "HH:mm", { timeZone: 'GMT' });
}
getTimeString("2020-02-11T18:48Z"); // => `01:48` but must be `18:48` in GMT
getTimeString("2020-02-11T18:48"); // => `18:48` - it's correct if I remove timezone info from the input string
01:48
looks like a value for my local timezone (Asia/Bangkok), but not GMT
Hello,
I have an issue with the lib, not sure if I am using it wrong or it's a bug.
Right now, it's 16:30 in CET. I changed my time zone to Sydney, so new Date()
will return Fri Mar 27 2020 02:36:03 GMT+1100 (Australia Sydney Standard Time)
. I would expect the code snipped down bellow to generate 2020-03-26
, instead I am getting 2020-03-28
. Am I doing something wrong?
const timeZone = "America/Chicago";
const inUTC = zonedTimeToUtc(new Date(), "Australia/Sydney");
const utcToZOned = utcToZonedTime(inUTC, timeZone);
const formated = format(utcToZOned, "yyyy-MM-dd", {timeZone});
console.log(formated)
Thank you for the amazing library! But there is one thing. I came here from react-native. It works perfectly for iOS but with android there's an issue I ran to:
import { utcToZonedTime, format } from 'date-fns-tz';
const TIME_ZONE = 'Europe/Berlin';
export const formatDate = (
date: Date | number,
currentFormat: string
): string => {
const utcTime = new Date(date);
const zonedTime = utcToZonedTime(utcTime, TIME_ZONE);
return format(zonedTime, currentFormat, { timeZone: TIME_ZONE });
};
currentFormat there is simple: 'dd.MM.y H:mm'
The problem is that using utcToZonedTime
throws an error: RangeError: timeZone is not supported.
I think it connected with Intl. Have anyone already faced it and, probably, found a solution?
Getting compilation error in version 1.0.7
Failed to compile.
./node_modules/date-fns-tz/esm/zonedTimeToUtc/index.js
Module not found: Error: Can't resolve 'date-fns/esm/_lib/cloneObject' in '/Users/{path}/node_modules/date-fns-tz/esm/zonedTimeToUtc'
> const dft = require('date-fns-tz')
undefined
> const nyDate = dft.toDate('2014-10-25T13:46:20 America/New_York')
undefined
> nyDate
'2014-10-25T17:46:20.000Z' // good
> dft.format(nyDate, 'yyyy-MM-dd HH:mm:ss zzz', { timeZone: 'America/New_York' })
'2014-10-26 04:46:20 GMT-4' // bad
I expected 2014-10-25 13:46:20 GMT-4
.
Another example
> const parisDate = dft.toDate('2019-10-30T05:00:00 Europe/Paris')
undefined
> parisDate
'2019-10-30T04:00:00.000Z' // good
> dft.format(parisDate, 'yyyy-MM-dd HH:mm:ss zzz', { timeZone: 'Europe/Paris' })
'2019-10-30 15:00:00 GMT+1' // bad
I expected 2019-10-30T05:00:00 GMT+1
Also, the examples in README are out of date, they throw RangeError: Format string contains an unescaped latin alphabet character 'Z'
. as is.
For reference
"date-fns": "^2.6.0",
"date-fns-tz": "^1.0.8",
Hi,
I'm unable to use an offset in the utcToZonedTime().
It works fine with a IANA string like America/Lima
- just when I do:
const localTimezoneOffset = new Date().getTimezoneOffset();
const localDate = utcToZonedTime(myUtcDateTime, localTimezoneOffset.toString());
return format(localDate, ("yyyy-mm-dd HH:mm:ss"))
When using formatWithOptions
from date-fns-tz/fp
I get the following error Cannot find module '../_lib/convertToFP/index.js'
. I've checked the installed module and it appears to be missing.
Would this library support .formatDistance() in the future? I personally use this function with i18n for "pt" language and i need to get timezone with new Date().getTimezoneOffset() / 60
but i dont know when do i need to sum
or subtract
from current time given to me from back end as ISO Format. Does this lib will sum or subtract hours (when formatting with .formatDistance()
), automatically?
Looks like this isn't quite dependency free.
Hi,
I'm using date-fns-tz
to display and parse dates in specific timezone.
toDate
gives me incorrect results for period of day (3:00 - 9:59) when DST:
dateFnsTz.toDate(
'2020-03-08 02:00', { timeZone: 'America/Los_Angeles' }
) // correct 2020-03-08 03:00
dateFnsTz.toDate(
'2020-03-08 03:00', { timeZone: 'America/Los_Angeles' }
) // incorrect 2020-03-08 04:00
dateFnsTz.toDate(
'2020-03-08 09:00', { timeZone: 'America/Los_Angeles' }
) // incorrect 2020-03-08 10:00
dateFnsTz.toDate(
'2020-03-08 10:00', { timeZone: 'America/Los_Angeles' }
) // correct 2020-03-08 10:00
Also, when I use dateFnsTz.format
, it returns the date in local timezone rather than the specified one:
dateFnsTz.format(
new Date('2020-03-03 10:00'),
'yyyy-MM-dd HH:mm',
{ timeZone: 'America/Los_Angeles' }
) // incorrect "2020-03-03 10:00 -08:00", should be "2020-03-03 00:00 -08:00" as I'm in +02:00 timezone
Hello there,
i discovered an issue using both zoneTimeToUtc
and utcToZonedTime
functions in order to convert a local (Berlin, Germany) Date to / from UTC. The following examples show that the Date won't get converted properly as the expected two hours delta is missing.
> new Date()
< Tue Oct 15 2019 13:49:21 GMT+0200 (Mitteleuropäische Sommerzeit)
> Intl.DateTimeFormat().resolvedOptions().timeZone
< "Germany/Berlin"
> date_fns_tz__WEBPACK_IMPORTED_MODULE_6__.zonedTimeToUtc(new Date(), 'Europe/Berlin')
< Tue Oct 15 2019 13:49:29 GMT+0200 (Mitteleuropäische Sommerzeit)
> date_fns_tz__WEBPACK_IMPORTED_MODULE_6__.utcToZonedTime(new Date(), 'Europe/Berlin')
< Tue Oct 15 2019 13:49:38 GMT+0200 (Mitteleuropäische Sommerzeit)
Fun fact: When using 'Etc/UTC' instead of 'Europe/Berlin' while calling the functions, it works. However, this feels liek it's not intended to be used like this.
Am I using the functions wrong or what's the problem? 😄
Thank you in advance!
I tried to do this utcToZonedTime(1581509131067, 'Etc/GMT-6'))
It returns Wed Feb 12 2020 12:05:31 (ignoring the given timezone),
Here is the Intl.DateTimeFormat implementation
Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZone: 'Etc/GMT-6',
}).format(1581509131067)
which understands the timezone and returns 2/12/2020, 6:05:31 PM
What is the date-fns-timezone equivalent to zonedTimeToUtc + utcToZonedTime?
The idea is to implement something like:
https://momentjs.com/timezone/docs/#/using-timezones/default-timezone/
So that everytime you use any date-fns related function, you always use the same timezone.
Hey,
It seems that there are const
declarations in the es bundle, e.g.:
date-fns-tz/esm/_lib/tzTokenizeDate/index.js
, l.23
const { type, value } = formatted[i]
I only have 12 occurences of const
in the whole output of my build, and I'm pretty sure it shouldn't occur, since IE doesn't support it.
Is there something I am missing here?
Thanks in advance!
This year for "America/New_York" the daylight saving ended on Nov 3, 02:00 where it turned back 01:00. My browser is on a local "America/New_York" system.
toDate() gets this correctly but not utcToZonedTime(). utcToZonedTime() adds an hour even before 02:00.
toDate('2019-11-03T03:00:00.000Z', { timeZone: 'America/New_York' })
// Sat Nov 02 2019 23:00:00 GMT-0400 (Eastern Daylight Time)
utcToZonedTime('2019-11-03T03:00:00.000Z', 'America/New_York')
// Sun Nov 03 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
toDate('2019-11-03T04:00:00.000Z', { timeZone: 'America/New_York' })
// Sun Nov 03 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
utcToZonedTime('2019-11-03T04:00:00.000Z', 'America/New_York')
// Sun Nov 03 2019 01:00:00 GMT-0400 (Eastern Daylight Time)
toDate('2019-11-03T05:00:00.000Z', { timeZone: 'America/New_York' })
// Sun Nov 03 2019 01:00:00 GMT-0400 (Eastern Daylight Time)
utcToZonedTime('2019-11-03T05:00:00.000Z', 'America/New_York')
// Sun Nov 03 2019 01:00:00 GMT-0500 (Eastern Standard Time)
toDate('2019-11-03T06:00:00.000Z', { timeZone: 'America/New_York' })
// Sun Nov 03 2019 01:00:00 GMT-0500 (Eastern Standard Time)
utcToZonedTime('2019-11-03T06:00:00.000Z', 'America/New_York')
// Sun Nov 03 2019 01:00:00 GMT-0500 (Eastern Standard Time)
toDate('2019-11-03T07:00:00.000Z', { timeZone: 'America/New_York' })
// Sun Nov 03 2019 02:00:00 GMT-0500 (Eastern Standard Time)
utcToZonedTime('2019-11-03T07:00:00.000Z', 'America/New_York')
// Sun Nov 03 2019 02:00:00 GMT-0500 (Eastern Standard Time)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.