A date and time library based on the C++11/14/17 header

Overview

Date

Build Status Join the chat at https://gitter.im/HowardHinnant/date


Try it out on wandbox!

Summary

This is actually several separate C++11/C++14/C++17 libraries:

  1. "date.h" is a header-only library which builds upon <chrono>. It adds some new duration types, and new time_point types. It also adds "field" types such as year_month_day which is a struct {year, month, day}. And it provides convenient means to convert between the "field" types and the time_point types.

  2. "tz.h" / "tz.cpp" are a timezone library built on top of the "date.h" library. This timezone library is a complete parser of the IANA timezone database. It provides for an easy way to access all of the data in this database, using the types from "date.h" and <chrono>. The IANA database also includes data on leap seconds, and this library provides utilities to compute with that information as well.

  3. "iso_week.h" is a header-only library built on top of the "date.h" library which implements the ISO week date calendar.

  4. "julian.h" is a header-only library built on top of the "date.h" library which implements a proleptic Julian calendar which is fully interoperable with everything above.

  5. "islamic.h" is a header-only library built on top of the "date.h" library which implements a proleptic Islamic calendar which is fully interoperable with everything above.

Standardization

Slightly modified versions of "date.h" and "tz.h" were voted into the C++20 working draft at the Jacksonville FL meeting on 2018-03-17:

Build & Test

The recommended way to use any of these libraries besides "tz.h" is to just include it. These are header-only libraries (except "tz.h").

To use "tz.h", there is a single source file (src/tz.cpp) that needs to be compiled. Here are the recommended directions: https://howardhinnant.github.io/date/tz.html#Installation.

One can run tests by cd'ing into the test subdirectory and running testit. There are known failures on all platforms except for macOS. And even on macOS if C++11 is used. If any of these failures present problems for you, there exist workarounds.

Additionally there is unsupported support for vcpkg and CMake. I don't personally use or maintain these systems as for me they cause more problems than they solve (for this small project). If you would like to contribute to these build systems please feel free to file a PR.

You can download and install Date using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install date

The Date port in vcpkg is updated by Microsoft team members and community contributors. If the version falls behind, please create an issue or pull request on the vcpkg repository.

You can optionally build using CMake. Here is a guide of how to build and test using the CMake Makefile generator.

mkdir build
cd build
cmake ../
cmake --build . --target testit # Consider '-- -j4' for multithreading

Projects using this library

If you would like your project (or product) on this list, just let me know.

Comments
  • tz.cpp should parse the compiled form of the TZDB, not the source

    tz.cpp should parse the compiled form of the TZDB, not the source

    I know you're writing only as an example, but given your notoriety, your source code might actually get used elsewhere.

    Please parse the compiled form of the database, after zic is done with it. In doing that, you should also set the default DB path to "/usr/share/zoneinfo", which should work just about anywhere that has a /usr directory.

    This should also eliminate the need to set a minimum year to be kept in memory, as the database is already pre-compiled.

    opened by thiagomacieira 45
  • Implement tzfiles and CMake

    Implement tzfiles and CMake

    This implements reading /usr/share/zone_info tzfiles (issue 1). Because they don't have the same information as the IANA rules I made a couple separate classes tzfile_zone and tzfile_db. I renamed time_zone and TZ_DB to tzrule_zone and tzrule_db respectively, and made typedefs for time_zone and TZ_DB for whatever is specified by TIMEZONE_DEFAULT macro. I renamed zoned_time to basic_zoned_time and it takes a class TimeZone as a template parameter. I also moved things like locate_zone, current_zone, get_tzdb, etc to the _zone and _db classes and inlined static versions to use time_zone and TZ_DB. I depated separating the 2 options into different headers and implementations but it would add up to 4 files to download for timezones to work.

    I modified validate.cpp for the new setup that can take tzfile or tzrule as a command line parameter and test that timezone. When I tested tzfile and tzrule I got the same output except the version line (tzfile doesn't have a version anywhere that I can find) and tzfile has a Factory timezone.

    I haven't tested on Windows so hopefully timezone mapping still works.

    I also added a CMakeLists.txt for cmake users and modified the *.fail.cpp files to do static_asserts so that they could be tested with ctest. I could do this as a separate PR or just leave it off if you would prefer to keep it as is. Also on my setup parse.pass.cpp is failing an assert, but I don't think it is related to anything I did.

    As for performance, running validate tzfile on my system normally takes ~2 seconds. Running validate tzrule takes ~14 seconds without having to download any files. tzfile requires no dependencies or system calls. If you need more up to date tzfiles than what is provided by OSX you can always run zic.

    opened by Erroneous1 42
  • Use realpath the determine the target of the localtime symlink

    Use realpath the determine the target of the localtime symlink

    The previous solution would fail, if /etc/localtime is a symlink to a symlink to the zone details. Using realpath resolves all potential symlinks and returns directly the path of interest.

    opened by Hubble1942 41
  • What did I do wrong?

    What did I do wrong?

    I tested the code below (latest master branch). With USE_OS_TZDB, on Ubuntu 20,04. It crashes with "Unknown error -1".

    using namespace date;
    using namespace std::chrono;
    
    printf("Searching TZDB\n");
    try {
    	auto &tzl = get_tzdb_list();
    	auto now = system_clock::now();
    	for (auto &curTzdb : tzl) {
    		for (auto &curTz : curTzdb.zones) {
    			auto name = curTz.name();
    			if (string::npos != name.find("New_York")) {
    				auto curInfo = curTz.get_info(now);
    				printf("%s %d %d\n", name.c_str(), (int)curInfo.offset.count(), (int)curInfo.save.count());
    			}
    		}
    	}
    } catch (const std::system_error &e) {
    	printf("%s\n", e.what());
    }
    
    duplicate 
    opened by librehome 30
  • How i can solve this three problems with datetime?

    How i can solve this three problems with datetime?

    Hi,

    First problem:

    • Can i use this library in mobile?

    Second problem: I have a problem that in our library that work with date and time: https://github.com/ezored/dependency-datetime/blob/master/build/source/cpp/ezored/time/DateTime.cpp#L8

    We receive datetime as string, but already in UTC. But when i use on the above method i got time in my current time zone, instead of a chrono object in UTC.

    Example:

    #include <iostream>
    #include <string>
    #include <chrono>
    #include <sstream>
    #include <iomanip>
    #include <cstdint>
    #include <ctime>
    
    int main()
    {
        std::tm tm = {};
        std::stringstream ss("2018-12-07 20:00:00");
        ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
        auto dt = std::chrono::system_clock::from_time_t(std::mktime(&tm));
    
        std::cout << (dt.time_since_epoch().count() / 1000000) << std::endl;
        
        // 1544212800 - 20:00 - correct (in utc)
        // 1544223600 - 11:00 - wrong (returned by count)
    
        return EXIT_SUCCESS;
    }
    

    I don't know how to solve it with pure c/c++.

    Third problem: How can i solve my problem above using this current library? It it works well i will convert all methods in my library to use this library.

    https://github.com/ezored/dependency-datetime/blob/master/build/source/cpp/ezored/time/DateTime.cpp

    Im searching for a solution a lot of time, but without solution now.

    opened by paulocoutinhox 28
  • Use string_literal for C++11 when possible

    Use string_literal for C++11 when possible

    Merged get_units code for C++11 and C++14, now string_literal are used for all non-custom ratio suffix, that are at most 2 characters [except: decaseconds, minutes, microseconds in char].

    This requires to special cases for string_literal, for C++11 mode:

    1. Constructor for from string or length 2 (3 elements array)
    2. Adding two string literals with size 1.
    opened by tomaszkam 27
  • Issue #88 regarding the ostream support for `date::format`

    Issue #88 regarding the ostream support for `date::format`

    PR for issue #88 created. As the additions to address the

    it will still have to create ostringstream internally for %z and for %S and %T

    are non-trivial (they are supported mainly in the subsecs.h file), it will take a bit to get through all the changes in the next comment)

    opened by acolomitchi 27
  • 4 tests failing when using system TZDB with GCC

    4 tests failing when using system TZDB with GCC

    When running testit from release 3.0.1 with OPTIONS='-DONLY_C_LOCALE=1 -DUSE_OS_TZDB=1', the tests posix/ptz.pass.cpp, solar_hijri_test/parse.pass.cpp, and tz_test/zoned_time.pass.cpp fail with error terminate called after throwing an instance of 'std::system_error' - what(): Unknown error -1. When testing the latest master, two tests from tz_test/zoned_time.pass.cpp fail.

    This happens when using GCC 10.3.0 on Debian Testing and GCC 11.2.0 on Debian Unstable, but not with Clang 11.1.0 on Debian Testing.

    Tested with 3.0.1 with https://github.com/HowardHinnant/date/commit/052eebaf0086e6bbc5ead01c3f1a8f02496aa701 applied and with latest master.

    opened by Tachi107 26
  • Runtime error on MacOS 10.13

    Runtime error on MacOS 10.13

    Presumably this is an issue with MacOS 10.13, as it worked on 10.12 last week.

    I can compile my code here:

    https://github.com/acgetchell/CDT-plusplus

    Your date time library is a subrepo in src/date:

    https://github.com/acgetchell/CDT-plusplus/tree/master/src/date

    Running the compiled code generates the following error:

    libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: default/America/Los_Angeles not found in timezone database
    Abort trap: 6
    
    opened by acgetchell 25
  • tz.cpp compilation error

    tz.cpp compilation error "no match for operator <<"

    I have tried to compile latest version of tz.cpp in my project (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4) with -DUSE_OS_TZDB and I get the following error:

    FAILED: /usr/bin/c++ -DUSE_OS_TZDB -I../. -I../../ibpp-2.5/core -I../../date -I/home/sur/Projects/boost_1_64_0 -std=c++14 -Wall -Wextra -g -MMD -MT CMakeFiles/crmintegration.dir/home/sur/Projects/date/tz.cpp.o -MF CMakeFiles/crmintegration.dir/home/sur/Projects/date/tz.cpp.o.d -o CMakeFiles/crmintegration.dir/home/sur/Projects/date/tz.cpp.o -c /home/sur/Projects/date/tz.cpp

    In file included from /home/sur/Projects/date/tz.cpp:86:0: /home/sur/Projects/date/tz_private.h: In function ‘std::ostream& date::detail::operator<<(std::ostream&, const date::detail::transition&)’: /home/sur/Projects/date/tz_private.h:294:12: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘const sys_seconds {aka const std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration >}’) os << t.timepoint << "Z "; ^

    Help me, please ! :)

    opened by pvsur 23
  • VS2013 build fixed

    VS2013 build fixed

    Hi Howard, I have finally managed to fix build of the library with Visual Stdio 2013 Update Pack 5. Please review and merge my changes into the mainstream version.

    opened by IvanPizhenko 20
  • docs: support dark color-scheme

    docs: support dark color-scheme

    This patch updates the html documentation to add the color-scheme meta element, signalling light and dark color scheme support, and updating the inline CSS styles to override some colors when dark mode is active, to make sure that the document is always readable.

    I've also cleaned up a bit the CSS styles, but without functional changes.

    I've only updated the latest standard revision (r7), but please let me know if I should revert changes to that file.

    Here's how it looks on my system; the dark scheme is provided by the browser:

    image

    image

    PS: to be clear, the page is rendered in dark mode only if the user has set dark mode in the browser/system settings

    opened by Tachi107 0
  • How to convert a date format with a time zone to time_t format?

    How to convert a date format with a time zone to time_t format?

    Hi! There is a string format: "2018-12-15 04:49:00+07" How do I get the time_t format? How do I get utc time?

    What if the format is like this: "2018-12-15 04:49:00.000+07" How can I get msec separately? Thanks!

    opened by vvpnet 1
  • build(cmake): always mark HAS_STRING_VIEW as part of the interface

    build(cmake): always mark HAS_STRING_VIEW as part of the interface

    If the library gets compiled with HAS_STRING_VIEW=1, consumers always need to link to the functions using std::string_view, as they are the only ones compiled into the shared library.

    If the library gets compiled with e.g. C++17 and the user uses an older standard version they'll still get an error, but an helpful compile-time one suggesting to enable C++17 mode, instead of a cryptic linking error.

    You can find a longer explanation here: https://github.com/HowardHinnant/date/pull/754#issuecomment-1361248007

    opened by Tachi107 0
  • How to convert timezone for format date string ?

    How to convert timezone for format date string ?

       I have one time string : `2022-12-13 10:32:06` . 
       I know  , the time string express the time of `Asia/Shanghai` timezone . 
    
       How to convert the time string to utc0 time date string : `2022-12-13 02:32:06` ?
    
    
       I know de-format date by `date::parse`
       I know format date by `date::format`
    
       how to convert timestamp(without timezone info) from one timezone to antoher timezone?
    
    opened by TomGarden 1
  • Quick question about casting day, month and year

    Quick question about casting day, month and year

    Quick question:

    Might you tell me the reasoning behind day and month types being cast to unsigned, while year types are cast to int?

    Thanks in advance.

    opened by QuantDevHacks 1
Releases(v3.0.1)
  • v3.0.1(May 18, 2021)

  • v3.0.0(Jun 9, 2020)

    This will likely be the final release of this library. From here you should migrate to C++20 as vendors begin to ship this library under namespace std::chrono.

    The master branch will continue to be bug fixed as bugs arise. However a subsequent release may or may not happen.

    The CMake support of this library is chaotic (to be kind). Personally I don't use it and instead follow the installation instructions found here: https://howardhinnant.github.io/date/tz.html#Installation (needed only for tz.h).

    Source code(tar.gz)
    Source code(zip)
  • v2.4.1(Mar 20, 2018)

    • Improved CMake support.
    • New names for months: January
    • New names for weekdays: Sunday
    • Parsing with %Ez now supports optional minutes field.
    • Miscellaneous bug fixes.
    Source code(tar.gz)
    Source code(zip)
  • v2.4(Dec 29, 2017)

    • Introduce CMake support.
    • Introduce clock_cast for converting between time_points of different clocks.
    • Allow conversion between zoned_time<Duration1, TimeZonePtr1> and zoned_time<Duration2, TimeZonePtr2>.
    • Miscellaneous porting and warning fixes.
    • Update to latest IANA website changes.
    Source code(tar.gz)
    Source code(zip)
  • 2.3(Oct 26, 2017)

    • Change directory structure to have include/ and src/.
    • Rename TZ_DB to tzdb (there's a backwards compatible typedef that may disappear in the future).
    • Specify constructors for nonexistent_local_time and ambiguous_local_time. This enables custom time zones to easily use them if needed.
    • Support multiple versions of the IANA database. The singleton is now a lock-free thread safe singly-linked list. The existing API implicitly references the front of this list.
    • Support custom time zones in zoned_time. See the Examples section in the tz documentation.
    • Add C++17 deduction guide support.
    • Give zoned_time a default constructor.
    • Give weekday_indexed a default constructor.
    • Add is_clock trait.
    • Add ONLY_C_LOCALE. Helps with systems with missing time_get/time_put facets.
    • Improve sub-picosecond support.
    • Minor bug and compatibility fixes.
    Source code(tar.gz)
    Source code(zip)
  • v2.2(Jun 18, 2017)

    • Rewrite of format and parse:
      • Many more types can be formatted and parsed with format and parse now.
        • durations, calendar types, tai_time, gps_time, ...
      • parse supports width parameter on many format flags.
      • to_stream and from_stream now return a reference to their streams.
      • Parsing whitespace very customizable with use of %n, %t and whitespace.
    • Using the OS-supplied timezone database now an option on Linux and macOS.
    • The downloaded timezone database install location can now be set at run time.
    • Improved support for basic_string with custom allocator.
    • duration I/O is merged into date.h.
    • Make zoned_time and time_of_day "deduction guide ready" for C++17.
      • This eliminates the need for make_zoned and make_time in C++17.
    • Many miscellaneous bug fixes.
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Jan 1, 2017)

    • Set USE_SHELL_API to default to 1. This better supports different flavors of linux.
    • INSTALL can now be configured on the command line.
    • Parsing and formatting fractional seconds can now handle super-second durations such as microfortnights.
    • Formatting and parsing rewritten, moved into date.h.
    • iOS support added.
    • Added trivial default constructors for most calendar types.
    • Add unary operators + and - to year.
    • Add to_stream.
    • Miscellaneous bug fixes.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jul 31, 2016)

    This is an API-breaking release relative to v1.0.0. The biggest difference is that day_point has been renamed to sys_days. This change was not done lightly, but I feel it was necessary to evolve the time zone library in the best direction. Indeed, the creation of the time zone library was itself a real-world test of the date library, and this change is a result of that test.

    The time zone library has seen significant changes with the introduction of local_time, local_days, and zoned_time. zoned_time, created with the helper functions make_zoned is now the most convenient high-level API to access time zone computations.

    Formatting and parsing utilities have been added to the time zone library. And "leap-second aware" clocks have also been added: utc_clock, tai_clock and gps_clock. This clocks have time_points that when subtracted across leap second insertions take those inserted leap seconds into account.

    Also new with this version of the time zone library is the ability to have the IANA time zone database automatically updated to the latest version on the first use by your application. This is the default setting for linux and macOS, and requires just a little extra installation effort on Windows.

    The header chrono_io.h provides streaming for the chrono::duration types. This gets rid of the need to use .count() and specify units manually when streaming durations.

    New calendars introduced:

    • Julian
    • Islamic

    Bug fixes include:

    • Much faster database initialization, even when compiled without optimizations on.
    • Port to RedHat
    • Support for wide streams
    • Fix overflow when minutes is 32 bits.
    Source code(tar.gz)
    Source code(zip)
Owner
Howard Hinnant
Howard Hinnant
Determine date based on days spent

date-based-on-days-spent Determine date based on days spent. Enter the number of days since the beginning of Gregorian calendar to get the date of tha

Amirhossein Aliakbarpour 1 Dec 6, 2021
Edited and relatively up-to-date xenos injector

Xenos Windows dll injector. Based on Blackbone library - https://github.com/DarthTon/Blackbone Changes from the original repository Up-to-date blackbo

null 5 Apr 18, 2022
Ashita v4 Beta release repository. Contains the current, most up-to-date, publicly released version of the Ashita v4 beta.

Ashita v4 Beta Release This repository contains the current, most up to date and publicly released version of the Ashita v4 beta. Lead Developers Ashi

Ashita 22 Dec 27, 2022
Date suivant le calendrier Républicain.

RDate date suivant le calendrier Républicain. Installation Avec Nix $ nix-env -if default.nix Sans Nix # Assurez-vous d'avoir un compilateur C et GNU

Wafelack 3 Sep 21, 2022
DimensionalAnalysis - A compact C++ header-only library providing compile-time dimensional analysis and unit awareness

Dimwits ...or DIMensional analysis With unITS is a C++14 library for compile-time dimensional analysis and unit awareness. Minimal Example #include <i

NJOY 8 Jul 8, 2022
Updates the Wii's current system time with the real world time.

Fix Wii System Time This is a homebrew tool I made for the Wii a while ago. It updates the current system time with the real world time via worldtimea

Puzzle 2 Nov 9, 2022
tiny_csg is a C++ library that generates meshes from brush-based level data and supports incremental updates (real-time CSG).

tiny_csg is a C++ library that generates meshes from brush-based level data and supports incremental updates (real-time CSG). It is intended to be used as a backend in 3d level editors and/or generators.

Luka Aleksić 35 Dec 18, 2022
A header maker, this project will create your header file with all your declaration in

Headermaker Install: git clone https://github.com/rmechety42/Headermaker.git cd Headermaker make install Usage: Headermaker src_folder_you_want_to

Rayan Mechety 35 Dec 8, 2022
Filament is a real-time physically based rendering engine for Android, iOS, Windows, Linux, macOS, and WebGL2

Filament Filament is a real-time physically based rendering engine for Android, iOS, Linux, macOS, Windows, and WebGL. It is designed to be as small a

Google 15.1k Jan 8, 2023
Improved version of real-time physics engine that couples FEM-based deformables and rigid body dynamics

Enhanced version of coupled FEM and constrained rigid body simulation Description This little playground aimed to test our Conjugate Gradients based M

Andrey Voroshilov 25 Apr 11, 2022
A run-time C++ library for working with units of measurement and conversions between them and with string representations of units and measurements

Units What's new Some of the CMake target names have changed in the latest release, please update builds appropriately Documentation A library that pr

Lawrence Livermore National Laboratory 112 Dec 14, 2022
Real-time oriented physics engine and library that's currently best suited for 2D games.

PlayRho A way to play with physical behaviors like the conservation of momentum. PlayRho is a real-time oriented physics engine and library that's cur

Louis Langholtz 94 Nov 25, 2022
header-only UTF-8 string functions based on STL-string

utf8_xxx header-only UTF-8 string functions based on STL-string size_t utf8_len(const std::string& _Str) std::string utf8_sub(const std::string& _Str,

Voidmatrix 2 Dec 27, 2021
An easy to build CO2 Monitor/Meter with Android and iOS App for real time visualization and charting of air data, data logger, a variety of communication options (BLE, WIFI, MQTT, ESP-Now) and many supported sensors.

CO2-Gadget An easy to build CO2 Monitor/Meter with cell phone App for real time visualization and charting of air data, datalogger, a variety of commu

Mariete 30 Dec 17, 2022
2D physics header-only library for videogames developed in C using raylib library.

Physac Physac is a small 2D physics engine written in pure C. The engine uses a fixed time-step thread loop to simluate physics. A physics step contai

Víctor Fisac 241 Dec 28, 2022
SSD1306 library and simple graphics core library based on Adafruit GFX Library.

Raspberry Pico SSD1306 + GFX Library Based on Adafruit GFX Library https://github.com/adafruit/Adafruit-GFX-Library Usage Hardware Connect your SSD130

Marcin Bober 31 Sep 1, 2022
Arduino library for ST Microelectronics VL53L5 multizone Time-of-Flight ranging sensor

VL53L5 Arduino library for ST Microelectronics VL53L5 multizone Time-of-Flight ranging camera (get it here!) Quickstart Connect I2C in the usual way (

Simon D. Levy 24 Dec 14, 2022
Pipet - c++ library for building lightweight processing pipeline at compile-time for string obfuscation, aes ciphering or whatever you want

Pipet Pipet is a lightweight c++17 headers-only library than can be used to build simple processing pipelines at compile time. Features Compile-time p

C. G. 60 Dec 12, 2022