GithubHelp home page GithubHelp logo

marnusw / date-fns-tz Goto Github PK

View Code? Open in Web Editor NEW
970.0 8.0 107.0 4.64 MB

Complementary library for date-fns v2 adding IANA time zone support

License: MIT License

JavaScript 60.17% TypeScript 39.83%
date zone-helpers zone-formatting iana date-fns timezone time utilities javascript

date-fns-tz's People

Contributors

adambard avatar anikeef avatar billnbell avatar brettwillis avatar bsvetlik avatar christopherklint97 avatar dependabot[bot] avatar grrowl avatar gugu avatar healqq avatar hyyan avatar leehaochen avatar luludan avatar make-github-pseudonymous-again avatar marnusw avatar mateuszkrzak avatar mediafreakch avatar millawell avatar patrik-csak avatar pcoffline avatar roman991 avatar semigradsky avatar simpod avatar thething avatar trevorsayre avatar vadimpopa avatar voliva avatar x7becka avatar ygormagalhaes avatar yharaskrik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

date-fns-tz's Issues

_lib/convertToFP/index.js is missing

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.

Etc/UTC Zone is not parsed correctly

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

Format method ignores the timeZone option

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

TypeScript compile error: Duplicate identifier 'Options'

Seeing an issuee when trying to use date-fns-tz in a TypeScript project.

Reproduction

Library Version
create-react-app 2.1.1
date-fns 2.0.0-alpha.26
date-fns-tz 0.1.2
  • Create a new project with create-react-app <projectName> --typescript
  • Open App.tsx and import date-fns and date-fns-tz, e.g:
import { addMinutes } from "date-fns";
import { utcToZonedTime } from 'date-fns-tz'
  • Run npm start / yarn start

Expected

App runs

Actual

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?

utcToZonedTime not accepting the offset

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"))

Summertime/Wintertime

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?

date-fns-tz v2 proposal

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.

@dcousens, @kroleg

Possible support for ".formatDistance()"?

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?

Timezone formatting between 00:00 to 01:00

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)

esm version imports non esm scripts from date-fns

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?

Invalid time zone specified: US/Pacific

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.

zonedTimeToUtc is not working when converting from 'Europe/Oslo'

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

utcToZonedTime() incorrect while toDate() correct around daylight saving time

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)

Flow: Namespace '"date-fns"' has no exported member 'Locale'

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.

Environments

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"
  ]
}

Getting cloneObject error

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'

Buggy zonedTimeToUtc / utcToZonedTime

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!

'Etc/GMT-6' timezone id and other Etc/GMT zones are not working with utcToZonedTime

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

zonedTimeToUtc is not working for timeZone Etc/GMT+6

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

utcToZonedTime returns next day when time matches offset

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!? 🤷‍♂️

utcToZonedTime returns next day when time matches offset

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

Example: https://codepen.io/atomcorp/pen/bGNZzZz

compatibility with ie11

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

zonedTimeToUtc in GMT-0752/GMT-0456 adds a minute to resulting date

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

Date format escaping doesn't work

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 [].

isEqual() is returning false in two equal dates

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

utcToZonedTime not working?

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.

utcToZonedTime "works" with imaginary time zones

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?

Millisecond precision

@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 ?

Incorrect zonedToUtc behavior with remote wall time that doesn't exist in browser timezone.

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

Runtime error on IE 11

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!

Unexpected result from format in README example

> 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",

format to ja shows GMT+9 rather than JST

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"

How to format to specific timezone

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

Timezone abbreviation doesn't seem to always work?

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.

The utcToZonedTime function adds an extra day if the timeZone parameter is "UTC" and the date is between "00:00:00.000Z" and "00:59:59.999Z"

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].

utcToZonedTime adds one day

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)

IE11 not accepting timezones

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']"

toDate works incorrectly near DST and format is not converting a date

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

Missing dependencies

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

Incorrect time for given timeZone

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!!

ISO-8601 With offset displaying local time

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?

Date incorrect date when using format with timeZone

  1. Computer time set to 2020-03-**03** 11:00 PM GMT-7 (California)
  2. At this exact moment GMT-03 should be the next day 2020-03-04

image

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"
  }

utcToZonedTime android Intl: timeZone is not supported

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.