packages feed

tztime (empty) → 0.1.0.0

raw patch · 17 files changed

+2340/−0 lines, 17 filesdep +basedep +deepseqdep +directorysetup-changed

Dependencies added: base, deepseq, directory, doctest-parallel, filepath, mtl, safe-exceptions, tasty, tasty-hunit-compat, template-haskell, text, th-test-utils, time, time-compat, tz, tztime

Files

+ LICENSE view
@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+    means each individual or legal entity that creates, contributes to+    the creation of, or owns Covered Software.++1.2. "Contributor Version"+    means the combination of the Contributions of others (if any) used+    by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+    means Covered Software of a particular Contributor.++1.4. "Covered Software"+    means Source Code Form to which the initial Contributor has attached+    the notice in Exhibit A, the Executable Form of such Source Code+    Form, and Modifications of such Source Code Form, in each case+    including portions thereof.++1.5. "Incompatible With Secondary Licenses"+    means++    (a) that the initial Contributor has attached the notice described+        in Exhibit B to the Covered Software; or++    (b) that the Covered Software was made available under the terms of+        version 1.1 or earlier of the License, but not also under the+        terms of a Secondary License.++1.6. "Executable Form"+    means any form of the work other than Source Code Form.++1.7. "Larger Work"+    means a work that combines Covered Software with other material, in+    a separate file or files, that is not Covered Software.++1.8. "License"+    means this document.++1.9. "Licensable"+    means having the right to grant, to the maximum extent possible,+    whether at the time of the initial grant or subsequently, any and+    all of the rights conveyed by this License.++1.10. "Modifications"+    means any of the following:++    (a) any file in Source Code Form that results from an addition to,+        deletion from, or modification of the contents of Covered+        Software; or++    (b) any new file in Source Code Form that contains any Covered+        Software.++1.11. "Patent Claims" of a Contributor+    means any patent claim(s), including without limitation, method,+    process, and apparatus claims, in any patent Licensable by such+    Contributor that would be infringed, but for the grant of the+    License, by the making, using, selling, offering for sale, having+    made, import, or transfer of either its Contributions or its+    Contributor Version.++1.12. "Secondary License"+    means either the GNU General Public License, Version 2.0, the GNU+    Lesser General Public License, Version 2.1, the GNU Affero General+    Public License, Version 3.0, or any later versions of those+    licenses.++1.13. "Source Code Form"+    means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+    means an individual or a legal entity exercising rights under this+    License. For legal entities, "You" includes any entity that+    controls, is controlled by, or is under common control with You. For+    purposes of this definition, "control" means (a) the power, direct+    or indirect, to cause the direction or management of such entity,+    whether by contract or otherwise, or (b) ownership of more than+    fifty percent (50%) of the outstanding shares or beneficial+    ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+    Licensable by such Contributor to use, reproduce, make available,+    modify, display, perform, distribute, and otherwise exploit its+    Contributions, either on an unmodified basis, with Modifications, or+    as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+    for sale, have made, import, and otherwise transfer either its+    Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+    or++(b) for infringements caused by: (i) Your and any other third party's+    modifications of Covered Software, or (ii) the combination of its+    Contributions with other software (except as part of its Contributor+    Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+    its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+    Form, as described in Section 3.1, and You must inform recipients of+    the Executable Form how they can obtain a copy of such Source Code+    Form by reasonable means in a timely manner, at a charge no more+    than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+    License, or sublicense it under different terms, provided that the+    license for the Executable Form does not attempt to limit or alter+    the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+*                                                                      *+*  6. Disclaimer of Warranty                                           *+*  -------------------------                                           *+*                                                                      *+*  Covered Software is provided under this License on an "as is"       *+*  basis, without warranty of any kind, either expressed, implied, or  *+*  statutory, including, without limitation, warranties that the       *+*  Covered Software is free of defects, merchantable, fit for a        *+*  particular purpose or non-infringing. The entire risk as to the     *+*  quality and performance of the Covered Software is with You.        *+*  Should any Covered Software prove defective in any respect, You     *+*  (not any Contributor) assume the cost of any necessary servicing,   *+*  repair, or correction. This disclaimer of warranty constitutes an   *+*  essential part of this License. No use of any Covered Software is   *+*  authorized under this License except under this disclaimer.         *+*                                                                      *+************************************************************************++************************************************************************+*                                                                      *+*  7. Limitation of Liability                                          *+*  --------------------------                                          *+*                                                                      *+*  Under no circumstances and under no legal theory, whether tort      *+*  (including negligence), contract, or otherwise, shall any           *+*  Contributor, or anyone who distributes Covered Software as          *+*  permitted above, be liable to You for any direct, indirect,         *+*  special, incidental, or consequential damages of any character      *+*  including, without limitation, damages for lost profits, loss of    *+*  goodwill, work stoppage, computer failure or malfunction, or any    *+*  and all other commercial damages or losses, even if such party      *+*  shall have been informed of the possibility of such damages. This   *+*  limitation of liability shall not apply to liability for death or   *+*  personal injury resulting from such party's negligence to the       *+*  extent applicable law prohibits such limitation. Some               *+*  jurisdictions do not allow the exclusion or limitation of           *+*  incidental or consequential damages, so this exclusion and          *+*  limitation may not apply to You.                                    *+*                                                                      *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++  This Source Code Form is subject to the terms of the Mozilla Public+  License, v. 2.0. If a copy of the MPL was not distributed with this+  file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++  This Source Code Form is "Incompatible With Secondary Licenses", as+  defined by the Mozilla Public License, v. 2.0.
+ README.md view
@@ -0,0 +1,239 @@+<!--+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0+-->++<!-- TOC ignore:true -->+# tztime++This package introduces:+* The `TZTime` data type, a valid and unambiguous point in time in some time zone.+* Functions for safely manipulating a `TZTime`.++Table of contents:+<!-- TOC -->++- [Examples](#examples)+  - [Manipulating a TZTime](#manipulating-a-tztime)+  - [Encoding / Decoding](#encoding--decoding)+- [Motivation](#motivation)++<!-- /TOC -->++# Examples++```hs+import Control.Arrow ((>>>))+import Data.Aeson+import Data.Aeson.QQ.Simple+import Data.Aeson.TH+import Data.Function ((&))+import Data.Time+import Data.Time.Clock.POSIX+import Data.Time.Compat+import Data.Time.TZInfo as TZI+import Data.Time.TZTime as TZ+import Data.Time.TZTime.QQ (tz)+```++## Manipulating a `TZTime`++```hs+λ> [tz|2022-03-04 10:15:00 +01:00 [Europe/Rome]|] & modifyLocal (+      addCalendarClip (calendarMonths 2 <> calendarDays 3) >>>+      atFirstDayOfWeekOnAfter Wednesday >>>+      atMidnight+    )+2022-05-11 00:00:00 +02:00 [Europe/Rome]+```++In spring in Havana, the clocks turn forward from 23:59 to 01:00.+So that day does not start at midnight, it starts at 01:00.++```hs+λ> atStartOfDay [tz|2022-03-13 10:45:00 [America/Havana]|]+2022-03-13 01:00:00 -04:00 [America/Havana]+```++In spring in Australia/Lord_Howe, the clocks turn forward 30 minutes at 02:00.+So 3 hours past 01:00 would actually be 04:30.++```hs+λ> :{+  addTime (hours 3) $+    TZ.fromLocalTime (TZI.fromLabel Australia__Lord_Howe) $+      LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 1 0 0)+:}+2022-10-02 04:30:00 +11:00 [Australia/Lord_Howe]+```++## Encoding / Decoding++Because there's no standard format for encoding a timezone identifier alongside a date/time/offset, most systems encode these two separately.+For example, if you're encoding to/decoding from JSON, you'll probably want to split a `TZTime` into+a `POSIXTime`/`UTCTime`/`ZonedTime` and a `TZIdentifier`, and encode them as separate fields.++```hs+data Message = MkMessage { sender :: Text, time :: ZonedTime, timezone :: TZIdentifier }+deriveFromJSON defaultOptions ''Message+```++To re-build a `TZTime`, you have to first fetch the time zone rules `TZInfo` for the given `TZIdentifier`+from the system's time zone database using `loadFromSystem` (or from the library's embedded database using `fromIdentifier`).++```hs+λ> json = encode [aesonQQ| { "sender": "john doe", "time": "2022-03-04T10:15:00+01:00", "timezone": "Europe/Rome" }|]++λ> Right message = eitherDecode' @Message json+λ> tzInfo <- TZI.loadFromSystem (timezone message)+λ> TZ.fromZonedTime tzInfo (time message)+2022-03-04 10:15:00 +01:00 [Europe/Rome]+```++If the encoded data is not meant to be read by other systems (and thus interoperability is not a concern),+then using the `Show`/`Read` instances to encode/decode as a single field is also an option.++```hs+λ> show [tz|2022-03-04 10:15:00 +01:00 [Europe/Rome]|]+"2022-03-04 10:15:00 +01:00 [Europe/Rome]"++λ> read @TZTime "2022-03-04 10:15:00 +01:00 [Europe/Rome]"+2022-03-04 10:15:00 +01:00 [Europe/Rome]+```++# Motivation++Note: We'll use the packages `time`, `time-compat` and `tz` for the examples below.++```hs+λ> :m +Data.Time.LocalTime Data.Time.Clock Data.Time.Calendar.Compat+λ> import qualified Data.Time.Zones as TZ+λ> import qualified Data.Time.Zones.All as TZ+```++Manipulating time in a given time zone is not trivial.++Depending on what you need to do, it may make sense to modify the local time-line+(i.e. using `time`'s [`LocalTime`](https://hackage.haskell.org/package/time/docs/Data-Time-LocalTime.html#t:LocalTime)),+or the universal time-line (i.e. convert the time to `UTCTime`, modify it, convert it back+to `LocalTime`).++For example, if you want to add a certain number of hours to the current time,+then modifying the local time-line may end up adding more time than you intended:++```hs+λ> -- It's 00:30 on 2022-11-06 in the America/Winnipeg time zone.+λ> tz = TZ.tzByLabel TZ.America__Winnipeg+λ> t1 = LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 0 30 0)+λ> t1+2022-11-06 00:30:00++λ> -- We naively add 4 hours to the local time.+λ> t2 = addLocalTime (secondsToNominalDiffTime 4 * 60 * 60) t1+λ> t2+2022-11-06 04:30:00++λ> -- Let's use the `tz` package to convert these times to UTC and+λ> -- see how many hours have actually passed between t1 and t2.+λ> TZ.LTUUnique t1utc _ = TZ.localTimeToUTCFull tz t1+λ> TZ.LTUUnique t2utc _ = TZ.localTimeToUTCFull tz t2+λ> nominalDiffTimeToSeconds (diffUTCTime t2utc t1utc) / 60 / 60+5.000000000000+```++We've accidentally landed 5 hours ahead, not 4 as we wanted.+This happened because on that day, at 01:59,+[the America/Winnipeg time zone switched](https://www.timeanddate.com/time/zone/canada/winnipeg?year=2022)+from the CDT offset (UTC-5) to the CST offset (UTC-6).+In other words, the clocks were turned back 1 hour, back to 01:00:00.++If the clocks had been turned forward, as is done in many time zones in spring, then we would have+added only 3 hours instead of 4.++If we add just 1 hour, we'll run into yet another issue:++```hs+λ> -- We naively add 1 hour to the local time.+λ> t2 = addLocalTime (secondsToNominalDiffTime 1 * 60 * 60) t1+λ> t2+2022-11-06 01:30:00++λ> -- Let's try converting t2 to UTC+λ> TZ.localTimeToUTCFull tz t2+LTUAmbiguous+  { _ltuFirst = 2022-11-06 06:30:00 UTC+  , _ltuSecond = 2022-11-06 07:30:00 UTC+  , _ltuFirstZone = CDT+  , _ltuSecondZone = CST+  }+```++We landed on an _ambiguous_ local time.+Since the clocks were turned back, there's an _overlap_: the time 01:30 happened _twice_ on that day.+Once at UTC-5 and again at UTC-6.++On the other hand, when the clock are turned forward, there is a _gap_ in the local time-line and we risk+accidentally constructing an _invalid_ `LocalTime` that never occurred in that time zone.++For these reasons, when adding a certain number of hours/minutes/seconds, you _probably_ want to do it+in the universal time-line instead.++----++Now say you want to add a certain number of days instead.+Doing that on the universal time-line may end up working not quite as expected:++```hs+λ> -- It's 23:30 on 2022-03-12 in the America/Winnipeg time zone.+λ> tz = TZ.tzByLabel TZ.America__Winnipeg+λ> t1 = LocalTime (YearMonthDay 2022 3 12) (TimeOfDay 23 30 0)++λ> -- Convert to UTC, add 1 day, convert back to our time zone.+λ> TZ.LTUUnique t1utc _ = TZ.localTimeToUTCFull tz t1+λ> t2utc = addUTCTime nominalDay t1utc+λ> TZ.utcToLocalTimeTZ tz t2utc+2022-03-14 00:30:00+```++We've accidentally landed _two_ days ahead instead of just one.+This happened because, on 2022-03-13, the clocks were turned forward 1 hour,+so that day only had 23 hours on that time zone.+Adding 24 hours on the universal time-line ended up being too much.++In the local time-line, some days may have 23 hours, 25 hours,+23 hours and 30 minutes (e.g. in the Australia/Lord_Howe time zone), etc,+depending on the offset transitions defined by each time zone.++For this reason, when you want to add days/weeks/months/years, you+_probably_ want to do it in the local time-line and then check if you landed+on a gap or an overlap and correct accordingly.++----++This package aims to:+1. make it easier to do "the right thing" and harder to do "the wrong thing".+2. ensure you don't accidentally end up with an invalid or ambiguous local time.++Here's how you'd do the above using `tztime`:++```hs+λ> import Data.Time.TZTime+λ> import Data.Time.TZTime.QQ (tz)+```++```hs+λ> t1 = [tz|2022-11-06 00:30:00 [America/Winnipeg]|]+λ> t2 = addTime (hours 4) t1+λ> t2+2022-11-06 03:30:00 -06:00 [America/Winnipeg]++λ> nominalDiffTimeToSeconds (diffTZTime t2 t1) / 60 / 60+4.000000000000+```++```hs+λ> t1 = [tz|2022-03-12 23:30:00 [America/Winnipeg]|]+λ> modifyLocal (addCalendarClip (calendarDays 1)) t1+2022-03-13 23:30:00 -05:00 [America/Winnipeg]+```
+ Setup.hs view
@@ -0,0 +1,6 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++import Distribution.Simple+main = defaultMain
+ doctest/Main.hs view
@@ -0,0 +1,11 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Main where++import System.Environment (getArgs)+import Test.DocTest (mainFromCabal)++main :: IO ()+main = mainFromCabal "tztime" =<< getArgs
+ src/Data/Time/TZInfo.hs view
@@ -0,0 +1,152 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Data.Time.TZInfo+  ( TZInfo(..)+  , TZIdentifier+  , utc+  -- * System's time zone database+  , loadFromSystem+  , loadFromFile+  , getCurrentTZInfo+  -- * Embedded time zone database+  , fromIdentifier+  , fromLabel+  -- ** TZLabel+  -- $tzlabel+  , TZ.TZLabel(..)+  ) where++import Control.DeepSeq (NFData)+import Data.Data (Data)+import Data.String (fromString)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Data.Time.Zones (TZ)+import Data.Time.Zones qualified as TZ+import Data.Time.Zones.All (TZLabel)+import Data.Time.Zones.All qualified as TZ+import GHC.Generics (Generic)+import System.Directory (getSymbolicLinkTarget)+import System.Environment (lookupEnv)+import System.FilePath (makeRelative)++{- | A time zone.++There are two main ways of loading a `TZInfo`:++1. Load it from the operating system's time zone database, using `loadFromSystem`, `loadFromFile`+   or `getCurrentTZInfo`.++2. Load it from the embedded database, using `fromIdentifier` or `fromLabel`.++    This package depends on the @tzdata@ package, which comes with an+    embedded [IANA](https://www.iana.org/time-zones) time zone database.++The embedded database has the benefit of being portable, that is, it works regardless+of your operating system.+The functions to read from the system database, on the other hand, aren't portable;+`loadFromSystem` and `getCurrentTZInfo` are not likely to work on Windows.++However, you have to make sure you're always using the latest version of @tzdata@+to get the latest updates.+The operating system's time zone database is usually easier to keep up-to-date.++-}+data TZInfo = TZInfo+  { tziIdentifier :: TZIdentifier+    -- ^ The time zone's identifier, e.g. @Europe/Paris@.+  , tziRules :: TZ+    -- ^ The time zone's rules describing offset changes.+  }+  deriving stock (Eq, Show, Data, Generic)+  deriving anyclass NFData++-- | A time zone's identifier, e.g. @Europe/Paris@.+type TZIdentifier = Text++-- | The UTC time zone.+utc :: TZInfo+utc = TZInfo "UTC" TZ.utcTZ++----------------------------------------------------------------------------+-- System's time zone database+----------------------------------------------------------------------------++-- | Looks for the time zone file in the system time zone directory, which is+-- @\/usr\/share\/zoneinfo@, or if the @TZDIR@ environment variable is+-- set, then there.+--+-- Note, this is unlikely to work on non-posix systems (e.g.,+-- Windows).+-- Use `fromIdentifier`, `fromLabel` or `loadFromFile` instead.+--+-- Throws an `Control.Exception.IOException` if the identifier is not found.+loadFromSystem :: TZIdentifier -> IO TZInfo+loadFromSystem ident =+  TZInfo ident <$> TZ.loadSystemTZ (T.unpack ident)++-- | Reads and parses a time zone information file (in @tzfile(5)@+-- aka. Olson file format).+loadFromFile :: TZIdentifier -> FilePath -> IO TZInfo+loadFromFile ident filepath =+  TZInfo ident <$> TZ.loadTZFromFile filepath++-- | Returns the local `TZInfo` based on the @TZ@ and @TZDIR@+-- environment variables.+--+-- See @tzset(3)@ for details, but basically:+--+-- * If @TZ@ environment variable is unset, we use @\/etc\/localtime@.+-- * If @TZ@ is set, but empty, we use `utc`.+-- * If @TZ@ is set and not empty, we use `loadFromSystem` to read that file.+getCurrentTZInfo :: IO TZInfo+getCurrentTZInfo =+  lookupEnv "TZ" >>= \case+    Nothing -> do+      filePath <- getSymbolicLinkTarget "/etc/localtime"+      let ident = fromString @TZIdentifier $ makeRelative "/usr/share/zoneinfo" filePath+      tz <- TZ.loadTZFromFile filePath+      pure $ TZInfo ident tz+    Just "" -> pure utc+    Just ident -> TZInfo (fromString ident) <$> TZ.loadSystemTZ ident++----------------------------------------------------------------------------+-- Embedded time zone database+----------------------------------------------------------------------------++-- | Look up a time zone in the @tzdata@'s embedded database.+fromIdentifier :: TZIdentifier -> Maybe TZInfo+fromIdentifier ident =+  TZInfo ident <$> TZ.tzByName (T.encodeUtf8 ident)++-- | Retrieves the time zone info for a "canonical" time zone+-- from @tzdata@'s embedded database.+fromLabel :: TZLabel -> TZInfo+fromLabel label =+  TZInfo+    (T.decodeUtf8 $ TZ.toTZName label)+    (TZ.tzByLabel label)++{- $tzlabel++`TZLabel` enumerates all the "canonical" time zones from the IANA database.++For example, the @2022a@ version of the IANA database defines @Europe/London@ as a+"canonical" time zone and @Europe/Jersey@, @Europe/Guernsey@ and @Europe/Isle_of_Man@ as+links to @Europe/London@.++@+Zone	Europe\/London	-0:01:15 -	LMT	1847 Dec  1  0:00s+			 ...+Link	Europe\/London	Europe\/Jersey+Link	Europe\/London	Europe\/Guernsey+Link	Europe\/London	Europe\/Isle_of_Man+@++Note that `fromLabel` only supports canonical time zone identifiers, whereas+`fromIdentifier` supports all time zone identifiers.++-}
+ src/Data/Time/TZTime.hs view
@@ -0,0 +1,346 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Data.Time.TZTime+  (+  -- * TZTime+    Internal.TZTime+  , Internal.tzTimeLocalTime+  , Internal.tzTimeTZInfo+  , Internal.tzTimeOffset+  -- * Constructors+  , getCurrentTZTime+  , Internal.fromUTC+  , Internal.fromPOSIXTime+  , Internal.fromZonedTime+  -- ** From @LocalTime@+  , Internal.fromLocalTime+  , Internal.fromLocalTimeStrict+  , Internal.fromLocalTimeThrow+  , Internal.unsafeFromLocalTime+  , Internal.TZError(..)+  -- * Conversions+  , Internal.toUTC+  , Internal.toPOSIXTime+  , Internal.toZonedTime+  , Internal.inTZ+  -- * Modifying a TZTime+  , atEarliestOffset+  , atLatestOffset+  , atStartOfDay+  -- * Universal time-line+  -- ** Adding seconds\/minutes\/hours+  , addTime+  , hours+  , minutes+  , seconds+  -- * Local time-line+  , modifyLocal+  , modifyLocalStrict+  , modifyLocalThrow+  -- ** Adding days\/weeks\/months\/years.+  -- | Use these with one of the @modifyLocal*@ functions.+  , addCalendarClip+  , addCalendarRollOver+  , calendarDays+  , calendarWeeks+  , calendarMonths+  , calendarYears+  -- ** Setting date\/time components.+  -- | Use these with one of the @modifyLocal*@ functions.+  , atYear+  , atMonthOfYear+  , atDayOfMonth+  , atDay+  , atHour+  , atMinute+  , atSecond+  , atTimeOfDay+  , atMidnight+  , atFirstDayOfWeekOnAfter+  -- * Other+  , diffTZTime+  ) where++import Control.Exception.Safe (MonadThrow, throwM)+import Control.Monad.Except (MonadError)+import Data.Fixed (Pico)+import Data.Time+  (CalendarDiffDays(..), Day, DayOfWeek(..), LocalTime(..), NominalDiffTime, TimeOfDay(..),+  addUTCTime, diffUTCTime, getCurrentTime, midnight, secondsToNominalDiffTime)+import Data.Time qualified as Time+import Data.Time.Calendar.Compat+  (DayOfMonth, MonthOfYear, Year, firstDayOfWeekOnAfter, pattern YearMonthDay)+import Data.Time.TZInfo+import Data.Time.TZTime.Internal as Internal++-- $setup+-- >>> import Data.Function ((&))+-- >>> import Data.Time.TZTime.QQ (tz)+-- >>> import Data.Time++----------------------------------------------------------------------------+-- Constructors+----------------------------------------------------------------------------++-- | Returns the current time with the local time zone information+-- based on the @TZ@ and @TZDIR@ environment variables.+--+-- See @tzset(3)@ for details, but basically:+--+-- * If @TZ@ environment variable is unset, we use @\/etc\/localtime@.+-- * If @TZ@ is set, but empty, we use `utc`.+-- * If @TZ@ is set and not empty, we use `loadFromSystem` to read that file.+getCurrentTZTime :: IO TZTime+getCurrentTZTime = do+  tzi <- getCurrentTZInfo+  utcNow <- getCurrentTime+  pure $ fromUTC tzi utcNow++----------------------------------------------------------------------------+-- Modifying a TZTime+----------------------------------------------------------------------------++-- | If this local time happens to be on an overlap,+-- switch to the earliest of the two offsets.+--+-- >>> atEarliestOffset [tz|2022-11-06 01:30:00 -06:00 [America/Winnipeg]|]+-- 2022-11-06 01:30:00 -05:00 [America/Winnipeg]+atEarliestOffset :: TZTime -> TZTime+atEarliestOffset tzt =+  case fromLocalTimeStrict (tzTimeTZInfo tzt) (tzTimeLocalTime tzt) of+    Left (TZOverlap _ earliest _) -> earliest+    _ -> tzt++-- | If this local time happens to be on an overlap,+-- switch to the latest of the two offsets.+--+-- >>> atLatestOffset [tz|2022-11-06 01:30:00 -05:00 [America/Winnipeg]|]+-- 2022-11-06 01:30:00 -06:00 [America/Winnipeg]+atLatestOffset :: TZTime -> TZTime+atLatestOffset tzt =+  case fromLocalTimeStrict (tzTimeTZInfo tzt) (tzTimeLocalTime tzt) of+    Left (TZOverlap _ _ latest) -> latest+    _ -> tzt++-- | Changes the time to the earliest time possible on that day.+--+-- This is usually 00:00, but, if, on that day:+--+-- * the clocks are turned, for example, from 23:59 to 01:00 and midnight is skipped,+--   this will return 01:00.+-- * the clocks are turned, for example, from 01:00 to 00:00 and midnight happens twice,+--   this will return the first occurrence (i.e. midnight at the earliest offset).+atStartOfDay :: TZTime -> TZTime+atStartOfDay tzt =+  case Internal.modifyLocalTimeLine atMidnight tzt of+    Right result -> result+    Left (TZGap _ _ after) -> after+    Left (TZOverlap _ atEarliestOffset _) -> atEarliestOffset++----------------------------------------------------------------------------+-- Adding seconds/minutes/hours.+----------------------------------------------------------------------------++{- | Adds the given amount of seconds++>>> [tz|2022-03-04 10:15:00 [Europe/Rome]|] & addTime (hours 2 + minutes 20)+2022-03-04 12:35:00 +01:00 [Europe/Rome]+-}+addTime :: NominalDiffTime -> TZTime -> TZTime+addTime = Internal.modifyUniversalTimeLine . addUTCTime++-- | A standard hour of 3600 seconds.+hours :: Pico -> NominalDiffTime+hours h = minutes (h * 60)++-- | A standard minute of 60 seconds.+minutes :: Pico -> NominalDiffTime+minutes m = seconds (m * 60)++seconds :: Pico -> NominalDiffTime+seconds = secondsToNominalDiffTime++----------------------------------------------------------------------------+-- Local time-line.+----------------------------------------------------------------------------++{- |+Modifies the date/time on the local time-line.++The result may:++* Land on a "gap", e.g. when the clocks are set forward in spring and a local time is skipped.+  When this happens, we shift the time forward by the duration of the gap.++    For example, on the 13th, the clocks skip one hour,+    from 01:59 (at the -06:00 offset) straight to 03:00 (at the -05:00 offset):++    >>> [tz|2022-03-12 02:15:00 -06:00 [America/Winnipeg]|] & modifyLocal (addCalendarClip (calendarDays 1))+    2022-03-13 03:15:00 -05:00 [America/Winnipeg]++* Land on an "overlap", e.g. when the clocks are set back in autumn and a local time happens twice.+  When this happens, we attempt to preserve the offset of the original `TZTime`.+  This ensures that @modifyLocal id == id@.+  If this is not possible, use the earliest of the two offsets.++    For example, on the 6th, the clocks are set back one hour,+    from 01:59 (at the -05:00 offset) back to 01:00 (at the -06:00 offset).+    This means the time 01:15 happens twice, first at -05:00 and then again at -06:00.++    >>> [tz|2022-11-05 01:15:00 -05:00 [America/Winnipeg]|] & modifyLocal (addCalendarClip (calendarDays 1))+    2022-11-06 01:15:00 -05:00 [America/Winnipeg]++    >>> [tz|2022-11-07 01:15:00 -06:00 [America/Winnipeg]|] & modifyLocal (addCalendarClip (calendarDays -1))+    2022-11-06 01:15:00 -06:00 [America/Winnipeg]++This behaviour should be suitable for most use cases.++Note: @modifyLocal (g . f)@ may not always be equivalent to+@modifyLocal g . modifyLocal f@.++If @modifyLocal f@ lands on a gap or an overlap, the time will be corrected as described above;+but there's a chance @modifyLocal (g . f)@ would skip right over+the gap/overlap and no correction is needed.+As a rule of thumb, apply all modifications to the local time-line in one go.++>>> import Control.Arrow ((>>>))+>>> :{+[tz|2022-03-04 10:15:00 +01:00 [Europe/Rome]|]+  & modifyLocal (+      addCalendarClip (calendarMonths 2 <> calendarDays 3) >>>+      atFirstDayOfWeekOnAfter Wednesday >>>+      atMidnight+    )+:}+2022-05-11 00:00:00 +02:00 [Europe/Rome]++-}+modifyLocal :: (LocalTime -> LocalTime) -> TZTime -> TZTime+modifyLocal f tzt =+  case modifyLocalStrict f tzt of+    Right result -> result+    Left (TZGap _ _ after) -> after+    Left (TZOverlap _ atEarliestOffset atLatestOffset)+      | tzTimeOffset atLatestOffset == tzTimeOffset tzt -> atLatestOffset+      | otherwise -> atEarliestOffset++-- | Similar to `modifyLocal`, but returns a `TZError`+-- if the result lands in a gap/overlap.+modifyLocalStrict :: MonadError TZError m => (LocalTime -> LocalTime) -> TZTime -> m TZTime+modifyLocalStrict = Internal.modifyLocalTimeLine++-- | Similar to `modifyLocal`, but throws a `TZError` in `MonadThrow`+-- if the result lands in a gap/overlap.+modifyLocalThrow :: MonadThrow m => (LocalTime -> LocalTime) -> TZTime -> m TZTime+modifyLocalThrow f =+  either throwM pure . modifyLocalStrict f++----------------------------------------------------------------------------+-- Adding days/weeks/months/years.+----------------------------------------------------------------------------++-- | Add the given number of months first and then the given number of days,+-- using the proleptic Gregorian calendar.+--+-- When adding months, days past the last day of the month are clipped to the last day.+-- For instance, 2005-01-30 + 1 month = 2005-02-28.+addCalendarClip :: CalendarDiffDays -> LocalTime -> LocalTime+addCalendarClip cdd lt = lt+  { localDay = Time.addGregorianDurationClip cdd $ localDay lt+  }++-- | Add the given number of months first and then the given number of days.+-- using the proleptic Gregorian calendar.+--+-- When adding months, days past the last day of the month roll over to the next month.+-- For instance, 2005-01-30 + 1 month = 2005-03-02.+addCalendarRollOver :: CalendarDiffDays -> LocalTime -> LocalTime+addCalendarRollOver cdd lt = lt+  { localDay = Time.addGregorianDurationRollOver cdd $ localDay lt+  }++calendarDays :: Integer -> CalendarDiffDays+calendarDays n = CalendarDiffDays 0 n++calendarWeeks :: Integer -> CalendarDiffDays+calendarWeeks n = CalendarDiffDays 0 (n * 7)++calendarMonths :: Integer -> CalendarDiffDays+calendarMonths n = CalendarDiffDays n 0++calendarYears :: Integer -> CalendarDiffDays+calendarYears n = CalendarDiffDays (n * 12) 0++----------------------------------------------------------------------------+-- Setting date/time components.+----------------------------------------------------------------------------++-- | Sets the year using the proleptic Gregorian calendar.+atYear :: Year -> LocalTime -> LocalTime+atYear y lt =+  let YearMonthDay _ moy dom = localDay lt+  in  lt { localDay = YearMonthDay y moy dom }++-- | Sets the month using the proleptic Gregorian calendar.+-- Invalid values will be clipped to the correct range.+atMonthOfYear :: MonthOfYear -> LocalTime -> LocalTime+atMonthOfYear moy lt =+  let YearMonthDay y _ dom = localDay lt+  in  lt { localDay = YearMonthDay y moy dom }++-- | Sets the day of month using the proleptic Gregorian calendar.+-- Invalid values will be clipped to the correct range.+atDayOfMonth :: DayOfMonth -> LocalTime -> LocalTime+atDayOfMonth dom lt =+  let YearMonthDay y m _ = localDay lt+  in  lt { localDay = YearMonthDay y m dom }++-- | Sets the day.+atDay :: Day -> LocalTime -> LocalTime+atDay day lt = lt { localDay = day }++atHour :: Int -> LocalTime -> LocalTime+atHour h lt = lt+  { localTimeOfDay = (localTimeOfDay lt) { todHour = h }+  }++atMinute :: Int -> LocalTime -> LocalTime+atMinute m lt = lt+  { localTimeOfDay = (localTimeOfDay lt) { todMin = m }+  }++atSecond :: Pico -> LocalTime -> LocalTime+atSecond s lt = lt+  { localTimeOfDay = (localTimeOfDay lt) { todSec = s }+  }++atTimeOfDay :: TimeOfDay -> LocalTime -> LocalTime+atTimeOfDay tod lt = lt { localTimeOfDay = tod }++-- | Sets the time to 00:00.+atMidnight :: LocalTime -> LocalTime+atMidnight = atTimeOfDay midnight++-- | Moves the date to the next given `DayOfWeek`.+-- If the current date is already a match, then the current date is returned unmodified.+--+-- >>> tzt = [tz|2022-02-24 10:00:00 [Europe/London]|]+-- >>> tzt & modifyLocal (atFirstDayOfWeekOnAfter Thursday)+-- 2022-02-24 10:00:00 +00:00 [Europe/London]+-- >>> tzt & modifyLocal (atFirstDayOfWeekOnAfter Wednesday)+-- 2022-03-02 10:00:00 +00:00 [Europe/London]+atFirstDayOfWeekOnAfter :: DayOfWeek -> LocalTime -> LocalTime+atFirstDayOfWeekOnAfter dow lt = lt+  { localDay = firstDayOfWeekOnAfter dow $ localDay lt+  }++----------------------------------------------------------------------------+-- Other+----------------------------------------------------------------------------++-- | Calculate the difference in seconds between two points in time.+diffTZTime :: TZTime -> TZTime -> NominalDiffTime+diffTZTime tzt1 tzt2 =+  diffUTCTime (toUTC tzt1) (toUTC tzt2)
+ src/Data/Time/TZTime/Internal.hs view
@@ -0,0 +1,346 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++{-# OPTIONS_HADDOCK not-home #-}++{-# LANGUAGE CPP #-}++module Data.Time.TZTime.Internal where++import Control.Applicative (optional)+import Control.DeepSeq (NFData)+import Control.Exception.Safe (Exception(..), MonadThrow, throwM)+import Control.Monad.Except (MonadError, throwError)+import Data.Data (Data)+import Data.Fixed (Fixed(..), Pico)+import Data.Function ((&))+import Data.Functor (void, (<&>))+import Data.List.NonEmpty (NonEmpty(..))+import Data.List.NonEmpty qualified as NE+import Data.Maybe (fromJust)+import Data.String (fromString)+import Data.Text qualified as T+import Data.Time (UTCTime, addUTCTime, secondsToNominalDiffTime)+import Data.Time qualified as Time+import Data.Time.Clock.POSIX (POSIXTime, posixSecondsToUTCTime, utcTimeToPOSIXSeconds)+import Data.Time.Compat (pattern YearMonthDay)+import Data.Time.Format.ISO8601 (iso8601Show)+import Data.Time.LocalTime+import Data.Time.TZInfo (TZIdentifier, TZInfo(..), fromIdentifier)+import Data.Time.Zones (LocalToUTCResult(..))+import Data.Time.Zones qualified as TZ+import GHC.Generics (Generic)+import GHC.Stack (HasCallStack)+import Text.ParserCombinators.ReadP (ReadP)+import Text.ParserCombinators.ReadP qualified as P++import Language.Haskell.TH.Syntax (Q, liftTyped)+#if MIN_VERSION_template_haskell(2,17,0)+import Language.Haskell.TH.Syntax (Code, Quote)+#else+import Language.Haskell.TH.Syntax (TExp)+#endif++{-# ANN module ("HLint: ignore Use fewer imports" :: String) #-}++----------------------------------------------------------------------------+-- TZTime+----------------------------------------------------------------------------++-- | A valid and unambiguous point in time in some time zone.+data TZTime = UnsafeTZTime+  { tztLocalTime :: LocalTime+  , tztTZInfo :: TZInfo+  , tztOffset :: Time.TimeZone+  }+  deriving stock (Eq, Data, Generic)+  deriving anyclass NFData++{- |+@yyyy-mm-dd hh:mm:ss[.sss] ±hh:mm [time zone]@.+Example: @2022-03-04 02:02:01 +01:00 [Europe/Rome]@.+-}+instance Show TZTime where+  show (UnsafeTZTime lt tzi offset) =+    show lt <> " " <> iso8601Show offset <> " [" <> tzIdent <> "]"+    where+      tzIdent = T.unpack $ tziIdentifier tzi++-- | The local time of this `TZTime`.+tzTimeLocalTime :: TZTime -> LocalTime+tzTimeLocalTime = tztLocalTime++-- | The time zone of this `TZTime`.+tzTimeTZInfo :: TZTime -> TZInfo+tzTimeTZInfo = tztTZInfo++-- | The offset observed in this time zone at this moment in time.+tzTimeOffset :: TZTime -> TimeZone+tzTimeOffset = tztOffset++----------------------------------------------------------------------------+-- Constructors+----------------------------------------------------------------------------++-- | Converts a `UTCTime` to the given time zone.+fromUTC :: TZInfo -> UTCTime -> TZTime+fromUTC tzi utct =+  UnsafeTZTime+    { tztLocalTime = TZ.utcToLocalTimeTZ (tziRules tzi) utct+    , tztTZInfo = tzi+    , tztOffset = TZ.timeZoneForUTCTime (tziRules tzi) utct+    }++-- | Converts a `POSIXTime` to the given time zone.+fromPOSIXTime :: TZInfo -> POSIXTime -> TZTime+fromPOSIXTime tzi = fromUTC tzi . posixSecondsToUTCTime++-- | Converts a `ZonedTime` to UTC and then to the given time zone.+fromZonedTime :: TZInfo -> ZonedTime -> TZTime+fromZonedTime tzi = fromUTC tzi . zonedTimeToUTC++-- | Attempted to construct a `TZTime` from an invalid or ambiguous `LocalTime`.+data TZError+  = TZOverlap+      LocalTime+      -- ^ The `LocalTime` is ambiguous.+      -- This usually happens when the clocks are set back in+      -- autumn and a local time happens twice.+      ~TZTime -- ^ The first occurrence of the given `LocalTime`, at the earliest offset.+      ~TZTime -- ^ The second occurrence of the given `LocalTime`, at the latest offset.+  | TZGap+      LocalTime+      -- ^ The `LocalTime` is invalid.+      -- This usually happens when the clocks are set forward in+      -- spring and a local time is skipped.+      ~TZTime -- ^ The given `LocalTime` adjusted back by the length of the gap.+      ~TZTime -- ^ The given `LocalTime` adjusted forward by the length of the gap.+  deriving stock (Eq, Data, Generic)+  deriving anyclass (NFData)++instance Show TZError where+  show = displayException++instance Exception TZError where+  displayException = \case+    TZGap lt tzt1 _ ->+      "The local time "+      <> show lt+      <> " is invalid in the time zone "+      <> show (tziIdentifier $ tztTZInfo tzt1)+      <> "."+    TZOverlap lt tzt1 tzt2 ->+      "The local time "+      <> show lt+      <> " is ambiguous in the time zone "+      <> show (tziIdentifier $ tztTZInfo tzt1)+      <> ": it is observed at the offsets "+      <> iso8601Show (tzTimeOffset tzt1)+      <> " and "+      <> iso8601Show (tzTimeOffset tzt2)+      <> "."++-- | Similar to `fromLocalTime`, but returns a `TZError`+-- if the local time is ambiguous/invalid.+fromLocalTimeStrict :: MonadError TZError m => TZInfo -> LocalTime -> m TZTime+fromLocalTimeStrict tzi lt =+  case TZ.localTimeToUTCFull (tziRules tzi) lt of+    LTUUnique _utc namedOffset ->+      pure $ UnsafeTZTime lt tzi namedOffset+    LTUAmbiguous _utc1 _utc2 namedOffset1 namedOffset2 ->+      throwError $ TZOverlap lt+        (UnsafeTZTime lt tzi namedOffset1)+        (UnsafeTZTime lt tzi namedOffset2)+    -- Note: LTUNone means the given `LocalTime` is invalid and lands on a "gap".+    -- The constructor contains:+    -- 1. The `UTCTime` corresponding to the `LocalTime` shifted forward by the duration of the gap.+    --    E.g., if it's a 1-hour gap, this will be the same as "toUTC (localTime + 1 hour)"+    -- 2. The offset observed in that time zone before the clocks changed.+    --+    -- From these 2 pieces of information, we can figure out the rest.+    --+    -- This approach works but is inefficient.+    -- TODO: reimplement parts of `localTimeToUTCFull` to make this more efficient.+    LTUNone utcAfter offsetBefore ->+      let+        offsetAfter = TZ.timeZoneForUTCTime (tziRules tzi) utcAfter+        gap = secondsToNominalDiffTime $ 60 *+          fromIntegral @Int @Pico (timeZoneMinutes offsetAfter - timeZoneMinutes offsetBefore)+        utcBefore = addUTCTime (- gap) utcAfter+      in+        throwError $ TZGap lt+          (UnsafeTZTime (TZ.utcToLocalTimeTZ (tziRules tzi) utcBefore) tzi offsetBefore)+          (UnsafeTZTime (TZ.utcToLocalTimeTZ (tziRules tzi) utcAfter) tzi offsetAfter)++-- | Constructs a `TZTime` from a local time in the given time zone.+--+-- * If the local time lands on a "gap" (e.g. when the clocks are set forward in spring and a local time is skipped),+--   we shift the time forward by the duration of the gap.+-- * If it lands on an "overlap" (e.g. when the clocks are set back in autumn and a local time happens twice),+--   we use the earliest offset.+fromLocalTime :: TZInfo -> LocalTime -> TZTime+fromLocalTime tzi lt =+  case fromLocalTimeStrict tzi lt of+    Right tzt -> tzt+    Left (TZGap _ _ after) -> after+    Left (TZOverlap _ atEarliestOffset _) -> atEarliestOffset++-- | Similar to `fromLocalTime`, but throws a `TZError` in `MonadThrow`+-- if the local time is ambiguous/invalid.+fromLocalTimeThrow :: MonadThrow m => TZInfo -> LocalTime -> m TZTime+fromLocalTimeThrow tzi =+  either throwM pure . fromLocalTimeStrict tzi++-- | Similar to `fromLocalTime`, but throws an `error`+-- if the local time is ambiguous/invalid.+unsafeFromLocalTime :: HasCallStack => TZInfo -> LocalTime -> TZTime+unsafeFromLocalTime tzi lt =+  case fromLocalTimeStrict tzi lt of+    Right tzt -> tzt+    Left err -> error $ "unsafeFromLocalTime: " <> displayException err++----------------------------------------------------------------------------+-- Conversions+----------------------------------------------------------------------------++-- | Converts this moment in time to the universal time-line.+toUTC :: TZTime -> UTCTime+toUTC tzt =+  localTimeToUTC (tzTimeOffset tzt) (tzTimeLocalTime tzt)++-- | Converts this moment in time to a POSIX timestamp.+toPOSIXTime :: TZTime -> POSIXTime+toPOSIXTime = utcTimeToPOSIXSeconds . toUTC++-- | Converts this moment in time to a `ZonedTime` (discarding time zone rules).+toZonedTime :: TZTime -> ZonedTime+toZonedTime tzt = ZonedTime (tzTimeLocalTime tzt) (tzTimeOffset tzt)++-- | Converts this moment in time to some other time zone.+inTZ :: TZInfo -> TZTime -> TZTime+inTZ tzi = fromUTC tzi . toUTC++----------------------------------------------------------------------------+-- Modifying a TZTime+----------------------------------------------------------------------------++-- | Modify this moment in time along the universal time-line.+modifyUniversalTimeLine :: (UTCTime -> UTCTime) -> TZTime -> TZTime+modifyUniversalTimeLine f tzt =+  fromUTC (tzTimeTZInfo tzt) . f . toUTC $ tzt++-- | Modify this moment in time along the local time-line.+modifyLocalTimeLine :: MonadError TZError m => (LocalTime -> LocalTime) -> TZTime -> m TZTime+modifyLocalTimeLine f tzt =+  fromLocalTimeStrict (tzTimeTZInfo tzt) . f . tzTimeLocalTime $ tzt++----------------------------------------------------------------------------+-- Parsing+----------------------------------------------------------------------------++{- |+@yyyy-mm-dd hh:mm:ss[.sss] [±hh:mm] [time zone]@.+Example: @2022-03-04 02:02:01 +01:00 [Europe/Rome]@.++The offset is optional, except when the local time is ambiguous+(i.e. when the clocks are set forward around that time in that time zone).++The offset can also be expressed using [military time zone abbreviations](https://www.timeanddate.com/time/zones/military),+and these time zones abbreviations as per RFC 822 section 5:+\"UTC\", \"UT\", \"GMT\", \"EST\", \"EDT\", \"CST\", \"CDT\", \"MST\", \"MDT\", \"PST\", \"PDT\".++Note: the time zone's rules are loaded from the embedded database using `fromIdentifier`.+-}+instance Read TZTime where+  readsPrec _ input = do+    ((lt, offsetMaybe, ident), input) <- P.readP_to_S readComponentsP input+    case getValidTZTimes lt ident >>= checkOffset offsetMaybe of+      Nothing -> []+      Just (tzt :| []) -> [(tzt, input)]+      Just (tzts) -> NE.toList tzts <&> \tzt -> (tzt, input)++readComponentsP :: ReadP (LocalTime, Maybe Time.TimeZone, TZIdentifier)+readComponentsP =+  (,,)+    <$> (P.readS_to_P $ reads @LocalTime)+    <*> (optional $ P.readS_to_P $ reads @Time.TimeZone)+    <*> readTZIdentP++readTZIdentP :: ReadP TZIdentifier+readTZIdentP = do+  P.skipSpaces+  void $ P.char '['+  fromString @TZIdentifier <$> P.manyTill P.get (P.char ']')++-- | Try to construct a `TZTime` from the given components.+getValidTZTimes :: MonadFail m => LocalTime -> TZIdentifier -> m (NonEmpty TZTime)+getValidTZTimes lt ident = do+  tzi <- case fromIdentifier ident of+    Nothing -> fail $ "Unknown time zone: '" <> T.unpack ident <> "'"+    Just tzi -> pure tzi+  case fromLocalTimeStrict tzi lt of+    Right tzt -> pure $ tzt :| []+    Left (TZOverlap _ tzt1 tzt2) -> pure $ tzt1 :| [tzt2]+    Left (TZGap _ tzt1 tzt2) ->+      fail $ "Invalid time: the clocks are set forward around this time.\n" <> mkSuggestions (tzt1 :| [tzt2])++-- | If the user specified an offset, check that it matches at least one of the valid `TZTime`s.+checkOffset :: MonadFail m => Maybe Time.TimeZone -> NonEmpty TZTime -> m (NonEmpty TZTime)+checkOffset offsetMaybe tzts =+  case offsetMaybe of+    Nothing -> pure tzts+    Just offset ->+      tzts+        & NE.filter (\tzt -> timeZoneMinutes offset == timeZoneMinutes (tzTimeOffset tzt))+        & NE.nonEmpty+        & \case+            Just validTzts -> pure validTzts+            Nothing -> fail $ "Invalid offset: " <> iso8601Show offset <> "\n" <> mkSuggestions tzts++mkSuggestions :: NonEmpty TZTime -> String+mkSuggestions tzts =+  "      Did you mean any of the following?" <> foldMap (\tzt -> "\n      - " <> show tzt) tzts++----------------------------------------------------------------------------+-- Template Haskell+----------------------------------------------------------------------------++readP_to_Q :: String -> ReadP a -> Q a+readP_to_Q input parser =+  case P.readP_to_S (parser <* P.eof) input of+    [] -> fail $ "Failed to parse: '" <> input <> "'"+    [(res, _)] -> pure res+    _ -> fail $ "Parsing is ambiguous: '" <> input <> "'"++#if MIN_VERSION_template_haskell(2,17,0)+liftTZTime :: Quote m => TZTime -> Code m TZTime+liftLocalTime :: Quote m => LocalTime -> Code m LocalTime+liftTimeZone :: Quote m => Time.TimeZone -> Code m Time.TimeZone+#else+liftTZTime :: TZTime -> Q (TExp TZTime)+liftTimeZone :: Time.TimeZone -> Q (TExp Time.TimeZone)+liftLocalTime :: LocalTime -> Q (TExp LocalTime)+#endif++-- | NOTE: this assumes the time zone identifier used to construct `TZTime` exists in the+-- embedded time zone database, i.e. it can be loaded using `fromIdentifier`.+liftTZTime tzt =+  [e||+    UnsafeTZTime+      $$(liftLocalTime $ tzTimeLocalTime tzt)+      (fromJust $ fromIdentifier $$(liftTyped ident))+      $$(liftTimeZone $ tzTimeOffset tzt)+  ||]+  where+    ident = tziIdentifier $ tzTimeTZInfo tzt++liftLocalTime (LocalTime (YearMonthDay yy mm dd) (TimeOfDay hh mmm (MkFixed ss))) =+  [e||+    LocalTime+      (YearMonthDay $$(liftTyped yy) $$(liftTyped mm) $$(liftTyped dd))+      (TimeOfDay $$(liftTyped hh) $$(liftTyped mmm) (MkFixed $$(liftTyped ss)))+  ||]++liftTimeZone (TimeZone tzMins tzSummer tzName) =+  [e|| TimeZone $$(liftTyped tzMins) $$(liftTyped tzSummer) $$(liftTyped tzName) ||]
+ src/Data/Time/TZTime/QQ.hs view
@@ -0,0 +1,70 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++{-# LANGUAGE CPP #-}++module Data.Time.TZTime.QQ+  ( tz+  ) where++import Data.List.NonEmpty (NonEmpty(..))+import Data.Time.TZTime.Internal as I+import Language.Haskell.TH (Exp, Q)+import Language.Haskell.TH.Quote+import Text.ParserCombinators.ReadP qualified as P++#if MIN_VERSION_template_haskell(2,17,0)+import Language.Haskell.TH.Syntax (unTypeCode)+#else+import Language.Haskell.TH.Syntax (unType)+#endif++{- |+Quasiquoter for parsing a `TZTime` at compile-time in the format:+@yyyy-mm-dd hh:mm:ss[.sss] [±hh:mm] [time zone]@.++The offset is optional, except when the local time is ambiguous+(i.e. when the clocks are set back around that time in that time zone).++The offset can also be expressed using [military time zone abbreviations](https://www.timeanddate.com/time/zones/military),+and these time zones abbreviations as per RFC 822 section 5:+\"UTC\", \"UT\", \"GMT\", \"EST\", \"EDT\", \"CST\", \"CDT\", \"MST\", \"MDT\", \"PST\", \"PDT\".++Note: the time zone's rules are loaded from the embedded database+using `Data.Time.TZInfo.fromIdentifier`.++>>> [tz|2022-03-04 10:15:40.123 [Europe/Rome]|]+2022-03-04 10:15:40.123 +01:00 [Europe/Rome]++>>> [tz|2022-11-06 01:30:00 [America/Winnipeg]|]+...+    • Ambiguous time: please specify an offset.+      Did you mean any of the following?+      - 2022-11-06 01:30:00 -05:00 [America/Winnipeg]+      - 2022-11-06 01:30:00 -06:00 [America/Winnipeg]+...++-}+tz :: QuasiQuoter+tz = QuasiQuoter+  { quoteExp = qexp+  , quotePat = \_ -> fail "Cannot use 'tz' as a pattern."+  , quoteType = \_ -> fail "Cannot use 'tz' as a type."+  , quoteDec = \_ ->fail "Cannot use 'tz' as a declaration."+  }+  where+    qexp :: String -> Q Exp+    qexp input = do+      (lt, offsetMaybe, ident) <- I.readP_to_Q input (I.readComponentsP <* P.skipSpaces)+      I.getValidTZTimes lt ident >>= I.checkOffset offsetMaybe >>= \case+        tzt :| [] -> toExp tzt+        tzts -> fail $ "Ambiguous time: please specify an offset.\n" <> I.mkSuggestions tzts++    toExp :: TZTime -> Q Exp+    toExp tzt =+#if MIN_VERSION_template_haskell(2,17,0)+      unTypeCode $ I.liftTZTime tzt+#else+      unType <$> I.liftTZTime tzt+#endif
+ test/Main.hs view
@@ -0,0 +1,13 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io>+--+-- SPDX-License-Identifier: MPL-2.0++module Main+  ( main+  ) where++import Test.Tasty+import Tree (tests)++main :: IO ()+main = tests >>= defaultMain
+ test/Test/Data/Time/TZTime.hs view
@@ -0,0 +1,149 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}++module Test.Data.Time.TZTime where++import Control.Arrow ((>>>))+import Data.Function ((&))+import Data.Time (DayOfWeek(..), LocalTime(..), TimeOfDay(..), TimeZone(..))+import Data.Time.Calendar.Compat (pattern YearMonthDay)+import Data.Time.TZInfo as TZI+import Data.Time.TZTime as TZT+import Data.Time.TZTime.Internal (TZTime(UnsafeTZTime))+import Test.Tasty (TestTree)+import Test.Tasty.HUnit+import Test.Utils++unit_atStartOfDay_at_gaps :: Assertion+unit_atStartOfDay_at_gaps = do+  -- On this date in Havana, at 23:59, the clocks are turned forward 1 hour,+  -- which means midnight never happens.+  --+  -- `atStartOfDay` should return the 01:00, the earliest time possible for that day.+  --+  -- See: https://www.timeanddate.com/time/zone/cuba/havana?year=2022+  let tz = TZI.fromLabel TZI.America__Havana+  let tzt = unsafeFromLocalTime tz (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 10 45 0))+  let result = atStartOfDay tzt++  result @?=+    UnsafeTZTime+      (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 1 0 0))+      tz+      (TimeZone (-4 * 60) True "CDT")++test_atStartOfDay_at_overlaps :: [TestTree]+test_atStartOfDay_at_overlaps =+  [ testCase "America/Havana" do+      -- On this date in Havana, at 01:00, the clocks are turned backwards 1 hour,+      -- which means midnight happens twice.+      --+      -- `atStartOfDay` should return the earliest of the two midnights.+      --+      -- See: https://www.timeanddate.com/time/zone/cuba/havana?year=2022+      let tz = TZI.fromLabel TZI.America__Havana+      let tzt = unsafeFromLocalTime tz (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 10 45 0))+      let result = atStartOfDay tzt++      result @?=+        UnsafeTZTime+          (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 0 0 0))+          tz+          (TimeZone (-4 * 60) True "CDT")++      -- Sanity checks+      -- Make sure this really is an overlap+      assertBool "Expected `result` to land on an overlap" $+        (result & toUTC) < (result & atLatestOffset & toUTC)+      -- This really is the earliest offset+      result @?= atEarliestOffset result++  , testCase "America/St_Johns" do+      -- Up until 2010, in America/St_Johns, the clocks were turned backwards+      -- 1 hour in autumn at 00:01 back to 23:01 the previous day, meaning the **date**+      -- would be moved backwards.+      --+      -- See:+      --   * https://davecturner.github.io/2017/12/27/timezone-curiosities.html+      --   * https://www.timeanddate.com/time/zone/canada/st-johns?year=2009+      let tz = TZI.fromLabel TZI.America__St_Johns+      let tzt = unsafeFromLocalTime tz (LocalTime (YearMonthDay 2009 11 1) (TimeOfDay 10 45 0))+      let result = atStartOfDay tzt++      result @?=+        UnsafeTZTime+          (LocalTime (YearMonthDay 2009 11 1) (TimeOfDay 0 0 0))+          tz+          (TimeZone (-2 * 60 - 30) True "NDT")++      -- Sanity checks+      -- Make sure this really is an overlap+      assertBool "Expected `result` to land on an overlap" $+        (result & toUTC) < (result & atLatestOffset & toUTC)+      -- This really is the earliest offset+      result @?= atEarliestOffset result+  ]++unit_addTime_and_diffTZTime_operate_on_the_universal_time_line :: Assertion+unit_addTime_and_diffTZTime_operate_on_the_universal_time_line = do+  -- At 01:59:59 on 2022-11-06, the America/Winnipeg time zone switches+  -- from CDT (UTC-5) to CST (UTC-6).+  -- In other words, the clocks are turned back 1 hour, back to 01:00:00.+  let local = LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 0 30 0)+  let tz = TZI.fromLabel TZI.America__Winnipeg+  let tzt = unsafeFromLocalTime tz local++  addTime (hours 1) tzt @?=+    UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0)) tz cdt++  addTime (hours 2) tzt @?=+    UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0)) tz cst++  addTime (hours 3) tzt @?=+    UnsafeTZTime (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 2 30 0)) tz cst++  diffTZTime (addTime (hours 1) tzt) tzt @?= hours 1+  diffTZTime (addTime (hours 2) tzt) tzt @?= hours 2+  diffTZTime (addTime (hours 3) tzt) tzt @?= hours 3++unit_composing_modifiers :: Assertion+unit_composing_modifiers = do+  let tz = TZI.fromLabel TZI.America__Havana+  let tzt = unsafeFromLocalTime tz (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 10 45 0))++  let result =+        tzt+          & modifyLocal (+              addCalendarClip (calendarMonths 2 <> calendarDays 3)+              >>> atFirstDayOfWeekOnAfter Wednesday+              >>> atMidnight+            )+          & atEarliestOffset+          & addTime (minutes 1 + seconds 20)++  result @?= unsafeFromLocalTime tz+    (LocalTime (YearMonthDay 2023 1 11) (TimeOfDay 0 1 20))++unit_addCalendar_zero_equals_id :: Assertion+unit_addCalendar_zero_equals_id = do+  -- With `modifyLocal`, adding 0 days should be equivalent+  -- to the identity function.+  let tz = TZI.fromLabel TZI.America__Winnipeg+  let mkLocalTime hh mm ss = LocalTime (YearMonthDay 2022 11 6) (TimeOfDay hh mm ss)++  check $ unsafeFromLocalTime tz (mkLocalTime 0 0 0)+  check $ unsafeFromLocalTime tz (mkLocalTime 2 0 0)+  check $ fromLocalTimeStrict tz (mkLocalTime 1 0 0) & \(Left (TZOverlap _ earliest _)) -> earliest+  check $ fromLocalTimeStrict tz (mkLocalTime 1 0 0) & \(Left (TZOverlap _ _ latest)) -> latest+  check $ fromLocalTimeStrict tz (mkLocalTime 1 30 0) & \(Left (TZOverlap _ earliest _)) -> earliest+  check $ fromLocalTimeStrict tz (mkLocalTime 1 30 0) & \(Left (TZOverlap _ _ latest)) -> latest+  check $ fromLocalTimeStrict tz (mkLocalTime 1 59 0) & \(Left (TZOverlap _ earliest _)) -> earliest+  check $ fromLocalTimeStrict tz (mkLocalTime 1 59 0) & \(Left (TZOverlap _ _ latest)) -> latest++  where+    check :: TZTime -> Assertion+    check tzt = do+      modifyLocal (addCalendarClip (calendarDays 0)) tzt @?= tzt
+ test/Test/Data/Time/TZTime/FromLocalTime.hs view
@@ -0,0 +1,135 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Test.Data.Time.TZTime.FromLocalTime where++import Data.Time (LocalTime(..), TimeOfDay(..), TimeZone(..))+import Data.Time.Calendar.Compat (pattern YearMonthDay)+import Data.Time.TZInfo as TZI+import Data.Time.TZTime as TZT+import Data.Time.TZTime.Internal (TZTime(UnsafeTZTime))+import Test.Tasty (TestTree)+import Test.Tasty.HUnit+import Test.Utils++unit_fromLocalTimeStrict_at_gaps :: Assertion+unit_fromLocalTimeStrict_at_gaps = do+  -- At 01:59:59 on 2022-03-13, the America/Winnipeg time zone switches+  -- from CST (UTC-6) to CDT (UTC-5).+  -- In other words, the clocks “skip” 1 hour, straight to 03:00:00.+  --+  -- See: https://www.timeanddate.com/time/zone/canada/winnipeg?year=2022+  --+  -- Therefore, the local time "2:15" is invalid.+  -- `fromLocalTimeStrict` should return the local time shifted backwards / forwards+  -- by the duration of the gap (+/- 1 hour).+  let local = LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 2 15 0)+  let tz = TZI.fromLabel TZI.America__Winnipeg++  TZT.fromLocalTimeStrict tz local @?= Left+    (TZGap local+      (UnsafeTZTime+        (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 1 15 0))+        tz cst+      )+      (UnsafeTZTime+        (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 3 15 0))+        tz cdt+      )+    )++test_fromLocalTimeStrict_at_odd_gaps :: [TestTree]+test_fromLocalTimeStrict_at_odd_gaps =+  [ testCase "Australia/Lord_Howe" do+      -- Australia/Lord_Howe turns the clocks forward 30 mins.+      --+      -- See: https://www.timeanddate.com/time/zone/australia/lord-howe-island?year=2022+      let local = LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 2 7 0)+      let tz = TZI.fromLabel TZI.Australia__Lord_Howe++      TZT.fromLocalTimeStrict tz local @?= Left+        (TZGap local+          (UnsafeTZTime+            (LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 1 37 0))+            tz+            (TimeZone (10 * 60 + 30) False "+1030")+          )+          (UnsafeTZTime+            (LocalTime (YearMonthDay 2022 10 2) (TimeOfDay 2 37 0))+            tz+            (TimeZone (11 * 60) True "+11")+          )+        )++  , testCase "Pacific/Apia" do+      -- On 2011-12-29, at 23:59:59, the island of Samoa switched from UTC-10 to UTC+14.+      -- In other words, the clocks were turned forward 24 hours,+      -- effectively skipping a whole calendar day (from 29 Dec to 31 Dec).+      --+      -- See: https://www.timeanddate.com/time/zone/samoa/apia?year=2011+      let local = LocalTime (YearMonthDay 2011 12 30) (TimeOfDay 10 7 0)+      let tz = TZI.fromLabel TZI.Pacific__Apia++      TZT.fromLocalTimeStrict tz local @?= Left+        (TZGap local+          (UnsafeTZTime+            (LocalTime (YearMonthDay 2011 12 29) (TimeOfDay 10 7 0))+            tz+            (TimeZone (-10 * 60) True "-10")+          )+          (UnsafeTZTime+            (LocalTime (YearMonthDay 2011 12 31) (TimeOfDay 10 7 0))+            tz+            (TimeZone (14 * 60) True "+14")+          )+        )+  ]++unit_fromLocalTimeStrict_at_overlaps :: Assertion+unit_fromLocalTimeStrict_at_overlaps = do+  -- At 01:59:59 on 2022-11-06, the America/Winnipeg time zone switches+  -- from CDT (UTC-5) to CST (UTC-6).+  -- In other words, the clocks are turned back 1 hour, back to 01:00:00.+  --+  -- See: https://www.timeanddate.com/time/zone/canada/winnipeg?year=2022+  --+  -- Therefore, the local time "01:15" happens twice: once at the -5 offset+  -- and again at the -6 offset.+  -- `fromLocalTimeStrict` should return both instants.+  let local = LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0)+  let tz = TZI.fromLabel TZI.America__Winnipeg++  TZT.fromLocalTimeStrict tz local @?= Left+    (TZOverlap local+      (UnsafeTZTime+        (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0))+        tz cdt+      )+      (UnsafeTZTime+        (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0))+        tz cst+      )+    )++unit_fromLocalTimeStrict_at_odd_overlaps :: Assertion+unit_fromLocalTimeStrict_at_odd_overlaps = do+  -- Australia/Lord_Howe turns the clocks backwards 30 mins.+  --+  -- See: https://www.timeanddate.com/time/zone/australia/lord-howe-island?year=2022+  let local = LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0)+  let tz = TZI.fromLabel TZI.Australia__Lord_Howe++  TZT.fromLocalTimeStrict tz local @?= Left+    (TZOverlap local+      (UnsafeTZTime+        (LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0))+        tz+        (TimeZone (11 * 60) True "+11")+      )+      (UnsafeTZTime+        (LocalTime (YearMonthDay 2022 4 3) (TimeOfDay 1 45 0))+        tz+        (TimeZone (10 * 60 + 30) False "+1030")+      )+    )
+ test/Test/Data/Time/TZTime/QQ.hs view
@@ -0,0 +1,97 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Test.Data.Time.TZTime.QQ where++import Data.List (intercalate)+import Data.Time (LocalTime(..), TimeOfDay(..), TimeZone)+import Data.Time.Calendar.Compat (pattern YearMonthDay)+import Data.Time.TZInfo as TZI+import Data.Time.TZTime as TZT+import Data.Time.TZTime.Internal (TZTime(UnsafeTZTime))+import Data.Time.TZTime.QQ (tz)+import Language.Haskell.TH (runQ)+import Language.Haskell.TH.Quote (quoteExp)+import Language.Haskell.TH.TestUtils (tryTestQ, unmockedState)+import Test.Tasty.HUnit++shouldFailWith :: String -> [String] -> Assertion+shouldFailWith input expectedErrorLines = do+  runQ (tryTestQ unmockedState (quoteExp tz input)) >>= \case+    Left err -> err @?= expectedError+    Right exp -> assertFailure $ unlines+      [ "Expected QQ to fail, but it succeeded with: "+      , show exp+      ]+  where+    expectedError = intercalate "\n" expectedErrorLines++unit_parses_valid_unambiguous_times :: Assertion+unit_parses_valid_unambiguous_times = do+  let expected = unsafeFromLocalTime (TZI.fromLabel TZI.Europe__Rome) (LocalTime (YearMonthDay 2022 3 4) (TimeOfDay 10 15 40.123))++  [tz|2022-03-04 10:15:40.123 [Europe/Rome]|] @?= expected+  [tz|2022-03-04 10:15:40.123 +01:00 [Europe/Rome]|] @?= expected++unit_fails_when_time_zone_is_unknown :: Assertion+unit_fails_when_time_zone_is_unknown = do+  "2022-01-01 01:02:03 [Narnia]" `shouldFailWith`+    ["Unknown time zone: 'Narnia'"]++unit_fails_when_time_is_valid_but_offset_is_invalid :: Assertion+unit_fails_when_time_is_valid_but_offset_is_invalid = do+  "2022-03-04 10:15:40.123 +03:00 [Europe/Rome]" `shouldFailWith`+    [ "Invalid offset: +03:00"+    , "      Did you mean any of the following?"+    , "      - 2022-03-04 10:15:40.123 +01:00 [Europe/Rome]"+    ]++unit_fails_when_time_lands_on_a_gap :: Assertion+unit_fails_when_time_lands_on_a_gap =+  "2022-03-13 02:30:00 [America/Winnipeg]" `shouldFailWith`+    [ "Invalid time: the clocks are set forward around this time."+    , "      Did you mean any of the following?"+    , "      - 2022-03-13 01:30:00 -06:00 [America/Winnipeg]"+    , "      - 2022-03-13 03:30:00 -05:00 [America/Winnipeg]"+    ]++unit_is_ambiguous_when_time_lands_on_an_overlap :: Assertion+unit_is_ambiguous_when_time_lands_on_an_overlap =+  "2022-11-06 01:30:00 [America/Winnipeg]" `shouldFailWith`+    [ "Ambiguous time: please specify an offset."+    , "      Did you mean any of the following?"+    , "      - 2022-11-06 01:30:00 -05:00 [America/Winnipeg]"+    , "      - 2022-11-06 01:30:00 -06:00 [America/Winnipeg]"+    ]++unit_is_not_ambiguous_when_time_lands_on_an_overlap_and_an_offset_is_specified :: Assertion+unit_is_not_ambiguous_when_time_lands_on_an_overlap_and_an_offset_is_specified = do+  [tz|2022-11-06 01:30:00 CDT [America/Winnipeg]|] @?=+    UnsafeTZTime+      (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0))+      (TZI.fromLabel TZI.America__Winnipeg)+      (read @TimeZone "CDT")+  [tz|2022-11-06 01:30:00 CST [America/Winnipeg]|] @?=+    UnsafeTZTime+      (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0))+      (TZI.fromLabel TZI.America__Winnipeg)+      (read @TimeZone "CST")++unit_fails_when_time_lands_on_an_overlap_and_the_offset_is_invalid :: Assertion+unit_fails_when_time_lands_on_an_overlap_and_the_offset_is_invalid = do+  "2022-11-06 01:30:00 +00:00 [America/Winnipeg]" `shouldFailWith`+    [ "Invalid offset: +00:00"+    , "      Did you mean any of the following?"+    , "      - 2022-11-06 01:30:00 -05:00 [America/Winnipeg]"+    , "      - 2022-11-06 01:30:00 -06:00 [America/Winnipeg]"+    ]++unit_fails_when_theres_extra_input :: Assertion+unit_fails_when_theres_extra_input = do+  "2022-03-04 10:15:40.123 [Europe/Rome] more input" `shouldFailWith`+    ["Failed to parse: '2022-03-04 10:15:40.123 [Europe/Rome] more input'"]++unit_ignores_surrounding_whitespace :: Assertion+unit_ignores_surrounding_whitespace = do+  [tz|   2022-03-04 10:15:40.123 [Europe/Rome]   |] @?= [tz|2022-03-04 10:15:40.123 [Europe/Rome]|]
+ test/Test/Data/Time/TZTime/Read.hs view
@@ -0,0 +1,89 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Test.Data.Time.TZTime.Read where++import Data.Functor ((<&>))+import Data.Time (LocalTime(..), TimeOfDay(..), TimeZone)+import Data.Time.Calendar.Compat (pattern YearMonthDay)+import Data.Time.TZInfo as TZI+import Data.Time.TZTime as TZT+import Data.Time.TZTime.Internal (TZTime(UnsafeTZTime))+import Data.Time.TZTime.QQ (tz)+import Test.Tasty.HUnit+import Text.Read (readEither)++unit_parses_valid_unambiguous_times :: Assertion+unit_parses_valid_unambiguous_times = do+  let expected = unsafeFromLocalTime (TZI.fromLabel TZI.Europe__Rome) (LocalTime (YearMonthDay 2022 3 4) (TimeOfDay 10 15 40.123))++  reads @TZTime "2022-03-04 10:15:40.123 [Europe/Rome]" @?= [(expected, "")]+  reads @TZTime "2022-03-04 10:15:40.123 +01:00 [Europe/Rome]" @?= [(expected, "")]++unit_fails_when_time_zone_is_unknown :: Assertion+unit_fails_when_time_zone_is_unknown = do+  reads @TZTime "2022-01-01 01:02:03 [Narnia]" @?= []++unit_fails_when_time_is_valid_but_offset_is_invalid :: Assertion+unit_fails_when_time_is_valid_but_offset_is_invalid = do+  reads @TZTime "2022-03-04 10:15:40.123 +03:00 [Europe/Rome]" @?= []++unit_fails_when_time_lands_on_a_gap :: Assertion+unit_fails_when_time_lands_on_a_gap =+  reads @TZTime "2022-03-13 02:30:00 [America/Winnipeg]" @?= []++unit_is_ambiguous_when_time_lands_on_an_overlap :: Assertion+unit_is_ambiguous_when_time_lands_on_an_overlap =+  reads @TZTime "2022-11-06 01:30:00 [America/Winnipeg]" @?=+    [ ( UnsafeTZTime+          (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0))+          (TZI.fromLabel TZI.America__Winnipeg)+          (read @TimeZone "CDT")+      , ""+      )+    , ( UnsafeTZTime+          (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0))+          (TZI.fromLabel TZI.America__Winnipeg)+          (read @TimeZone "CST")+      , ""+      )+    ]++unit_is_not_ambiguous_when_time_lands_on_an_overlap_and_an_offset_is_specified :: Assertion+unit_is_not_ambiguous_when_time_lands_on_an_overlap_and_an_offset_is_specified = do+  reads @TZTime "2022-11-06 01:30:00 CDT [America/Winnipeg]" @?=+    [ ( UnsafeTZTime+          (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0))+          (TZI.fromLabel TZI.America__Winnipeg)+          (read @TimeZone "CDT")+      , ""+      )+    ]+  reads @TZTime "2022-11-06 01:30:00 CST [America/Winnipeg]" @?=+    [ ( UnsafeTZTime+          (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 30 0))+          (TZI.fromLabel TZI.America__Winnipeg)+          (read @TimeZone "CST")+      , ""+      )+    ]++unit_fails_when_time_lands_on_an_overlap_and_the_offset_is_invalid :: Assertion+unit_fails_when_time_lands_on_an_overlap_and_the_offset_is_invalid = do+  reads @TZTime "2022-11-06 01:30:00 +00:00 [America/Winnipeg]" @?= []++unit_returns_remaining_input :: Assertion+unit_returns_remaining_input = do+  (reads @TZTime "2022-03-04 10:15:40.123 [Europe/Rome] more input" <&> snd) @?= [" more input"]+  (reads @TZTime "2022-03-04 10:15:40.123 +01:00 [Europe/Rome] more input" <&> snd) @?= [" more input"]++unit_read_show_roundtrip :: Assertion+unit_read_show_roundtrip = do+  check [tz|2022-03-04 10:15:40.123 [Europe/Rome]|]+  check [tz|2022-03-04 10:15:40 +01:00 [Europe/Rome]|]+  check [tz|2022-11-06 01:30:00 CDT [America/Winnipeg]|]+  check [tz|2022-11-06 01:30:00 CST [America/Winnipeg]|]+  where+    check :: HasCallStack => TZTime -> Assertion+    check tzt = readEither @TZTime (show tzt) @?= Right tzt
+ test/Test/Data/Time/TZTime/Show.hs view
@@ -0,0 +1,31 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Test.Data.Time.TZTime.Show where++import Control.Exception (displayException)+import Data.Bifunctor (first)+import Data.Time (LocalTime(..), TimeOfDay(..))+import Data.Time.Calendar.Compat (pattern YearMonthDay)+import Data.Time.TZInfo as TZI+import Data.Time.TZTime as TZT+import Data.Time.TZTime.QQ (tz)+import Test.Tasty.HUnit++unit_TZTime :: Assertion+unit_TZTime = do+  show [tz|2022-03-04 02:02:01 +01:00 [Europe/Rome]|] @?=+    "2022-03-04 02:02:01 +01:00 [Europe/Rome]"++unit_TZError :: Assertion+unit_TZError = do+  let tz = TZI.fromLabel TZI.America__Winnipeg++  first displayException+    (TZT.fromLocalTimeStrict tz (LocalTime (YearMonthDay 2022 3 13) (TimeOfDay 2 15 0))) @?= Left+    "The local time 2022-03-13 02:15:00 is invalid in the time zone \"America/Winnipeg\"."++  first displayException+    (TZT.fromLocalTimeStrict tz (LocalTime (YearMonthDay 2022 11 6) (TimeOfDay 1 15 0))) @?= Left+    "The local time 2022-11-06 01:15:00 is ambiguous in the time zone \"America/Winnipeg\": it is observed at the offsets -05:00 and -06:00."
+ test/Test/Utils.hs view
@@ -0,0 +1,13 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io/>+--+-- SPDX-License-Identifier: MPL-2.0++module Test.Utils where++import Data.Time (TimeZone)++cst :: TimeZone+cst = read "CST"++cdt :: TimeZone+cdt = read "CDT"
+ test/Tree.hs view
@@ -0,0 +1,7 @@+-- SPDX-FileCopyrightText: 2022 Serokell <https://serokell.io>+--+-- SPDX-License-Identifier: MPL-2.0++{-# OPTIONS_GHC -Wno-missing-kind-signatures #-}++{-# OPTIONS_GHC -F -pgmF tasty-discover -optF --tree-display -optF --generated-module -optF Tree #-}
+ tztime.cabal view
@@ -0,0 +1,263 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.34.4.+--+-- see: https://github.com/sol/hpack++name:           tztime+version:        0.1.0.0+synopsis:       Safe timezone-aware handling of time.+description:    This package introduces:+                .+                * The `TZTime` data type, a valid and unambiguous point in time in some time zone.+                * Functions for safely manipulating a `TZTime`.+category:       Time+homepage:       https://github.com/serokell/tztime+bug-reports:    https://github.com/serokell/tztime/issues+author:         Serokell+maintainer:     Serokell <hi@serokell.io>+copyright:      2022 Serokell <https://serokell.io>+license:        MPL-2.0+license-file:   LICENSE+build-type:     Simple+tested-with:+    GHC == 8.10.7+  , GHC == 9.0.2+  , GHC == 9.2.4+extra-source-files:+    README.md++source-repository head+  type: git+  location: https://github.com/serokell/tztime++library+  exposed-modules:+      Data.Time.TZInfo+      Data.Time.TZTime+      Data.Time.TZTime.Internal+      Data.Time.TZTime.QQ+  other-modules:+      Paths_tztime+  hs-source-dirs:+      src+  default-extensions:+      AllowAmbiguousTypes+      ApplicativeDo+      BangPatterns+      BlockArguments+      ConstraintKinds+      DataKinds+      DefaultSignatures+      DeriveAnyClass+      DeriveDataTypeable+      DeriveFoldable+      DeriveFunctor+      DeriveGeneric+      DeriveLift+      DeriveTraversable+      DerivingStrategies+      DerivingVia+      EmptyCase+      FlexibleContexts+      FlexibleInstances+      FunctionalDependencies+      GADTs+      GeneralizedNewtypeDeriving+      ImportQualifiedPost+      InstanceSigs+      LambdaCase+      MultiParamTypeClasses+      MultiWayIf+      NamedFieldPuns+      NegativeLiterals+      NumDecimals+      NumericUnderscores+      OverloadedLabels+      OverloadedStrings+      PatternSynonyms+      PolyKinds+      QuantifiedConstraints+      QuasiQuotes+      RankNTypes+      RecordWildCards+      RecursiveDo+      ScopedTypeVariables+      StandaloneDeriving+      StandaloneKindSignatures+      StrictData+      TemplateHaskell+      TupleSections+      TypeApplications+      TypeFamilies+      TypeOperators+      UndecidableInstances+      UndecidableSuperClasses+      ViewPatterns+  ghc-options: -Weverything -Wno-implicit-prelude -Wno-name-shadowing -Wno-missing-import-lists -Wno-missing-export-lists -Wno-unsafe -Wno-safe -Wno-missing-safe-haskell-mode -Wno-prepositive-qualified-module -Wno-monomorphism-restriction -Wno-missed-specialisations -Wno-all-missed-specialisations+  build-depends:+      base >=4.7 && <5+    , deepseq+    , directory >=1.3.1.0+    , filepath+    , mtl+    , safe-exceptions+    , template-haskell >=2.16.0.0+    , text+    , time >=1.9.2+    , time-compat >=1.9.4+    , tz >=0.1.3.4+  if impl(ghc >= 9.2)+    ghc-options: -Wno-missing-kind-signatures+  default-language: Haskell2010++test-suite tztime-doctest+  type: exitcode-stdio-1.0+  main-is: Main.hs+  other-modules:+      Paths_tztime+  hs-source-dirs:+      doctest+  default-extensions:+      AllowAmbiguousTypes+      ApplicativeDo+      BangPatterns+      BlockArguments+      ConstraintKinds+      DataKinds+      DefaultSignatures+      DeriveAnyClass+      DeriveDataTypeable+      DeriveFoldable+      DeriveFunctor+      DeriveGeneric+      DeriveLift+      DeriveTraversable+      DerivingStrategies+      DerivingVia+      EmptyCase+      FlexibleContexts+      FlexibleInstances+      FunctionalDependencies+      GADTs+      GeneralizedNewtypeDeriving+      ImportQualifiedPost+      InstanceSigs+      LambdaCase+      MultiParamTypeClasses+      MultiWayIf+      NamedFieldPuns+      NegativeLiterals+      NumDecimals+      NumericUnderscores+      OverloadedLabels+      OverloadedStrings+      PatternSynonyms+      PolyKinds+      QuantifiedConstraints+      QuasiQuotes+      RankNTypes+      RecordWildCards+      RecursiveDo+      ScopedTypeVariables+      StandaloneDeriving+      StandaloneKindSignatures+      StrictData+      TemplateHaskell+      TupleSections+      TypeApplications+      TypeFamilies+      TypeOperators+      UndecidableInstances+      UndecidableSuperClasses+      ViewPatterns+  ghc-options: -Weverything -Wno-implicit-prelude -Wno-name-shadowing -Wno-missing-import-lists -Wno-missing-export-lists -Wno-unsafe -Wno-safe -Wno-missing-safe-haskell-mode -Wno-prepositive-qualified-module -Wno-monomorphism-restriction -Wno-missed-specialisations -Wno-all-missed-specialisations -threaded+  build-depends:+      base+    , doctest-parallel+  if impl(ghc >= 9.2)+    ghc-options: -Wno-missing-kind-signatures+  default-language: Haskell2010++test-suite tztime-test+  type: exitcode-stdio-1.0+  main-is: Main.hs+  other-modules:+      Test.Data.Time.TZTime+      Test.Data.Time.TZTime.FromLocalTime+      Test.Data.Time.TZTime.QQ+      Test.Data.Time.TZTime.Read+      Test.Data.Time.TZTime.Show+      Test.Utils+      Tree+      Paths_tztime+  hs-source-dirs:+      test+  default-extensions:+      AllowAmbiguousTypes+      ApplicativeDo+      BangPatterns+      BlockArguments+      ConstraintKinds+      DataKinds+      DefaultSignatures+      DeriveAnyClass+      DeriveDataTypeable+      DeriveFoldable+      DeriveFunctor+      DeriveGeneric+      DeriveLift+      DeriveTraversable+      DerivingStrategies+      DerivingVia+      EmptyCase+      FlexibleContexts+      FlexibleInstances+      FunctionalDependencies+      GADTs+      GeneralizedNewtypeDeriving+      ImportQualifiedPost+      InstanceSigs+      LambdaCase+      MultiParamTypeClasses+      MultiWayIf+      NamedFieldPuns+      NegativeLiterals+      NumDecimals+      NumericUnderscores+      OverloadedLabels+      OverloadedStrings+      PatternSynonyms+      PolyKinds+      QuantifiedConstraints+      QuasiQuotes+      RankNTypes+      RecordWildCards+      RecursiveDo+      ScopedTypeVariables+      StandaloneDeriving+      StandaloneKindSignatures+      StrictData+      TemplateHaskell+      TupleSections+      TypeApplications+      TypeFamilies+      TypeOperators+      UndecidableInstances+      UndecidableSuperClasses+      ViewPatterns+  ghc-options: -Weverything -Wno-implicit-prelude -Wno-name-shadowing -Wno-missing-import-lists -Wno-missing-export-lists -Wno-unsafe -Wno-safe -Wno-missing-safe-haskell-mode -Wno-prepositive-qualified-module -Wno-monomorphism-restriction -Wno-missed-specialisations -Wno-all-missed-specialisations -threaded -rtsopts -with-rtsopts=-N+  build-tool-depends:+      tasty-discover:tasty-discover+  build-depends:+      base >=4.7 && <5+    , tasty+    , tasty-hunit-compat+    , template-haskell+    , th-test-utils+    , time+    , time-compat+    , tztime+  if impl(ghc >= 9.2)+    ghc-options: -Wno-missing-kind-signatures+  default-language: Haskell2010