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

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.

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

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

  • 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());
    }
    
  • 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.

  • 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.
  • 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)

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

  • 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
    
  • 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 ! :)

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

  • 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

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

  • 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

  • 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?
    
  • 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.

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

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

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

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

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

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

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

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.

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

Dec 8, 2022
Filament is a real-time physically based rendering engine for Android, iOS, Windows, Linux, macOS, and WebGL2
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

Jan 8, 2023
Improved version of real-time physics engine that couples FEM-based deformables and rigid body dynamics
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

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

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

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,

Dec 27, 2021
2D physics header-only library for videogames developed in C using raylib library.
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

Dec 28, 2022
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.
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

Dec 17, 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

Sep 1, 2022
Arduino library for ST Microelectronics VL53L5 multizone Time-of-Flight ranging sensor
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 (

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

Dec 12, 2022