|
Time Shield Library 2.0.0
C++ library for working with time
|
Version: 2.0.0
Header-only C++11–17 library for time conversions, parsing, formatting, ISO 8601, time zones, timers, astronomy helpers, and optional NTP services.
The Time Shield Library is a comprehensive C++ library designed for time manipulation, formatting, and conversion. It was built for practical and engineering tasks, especially in constrained or performance-critical environments.
Unlike std::chrono or more academic libraries like HowardHinnant/date, Time Shield is designed to be simple, portable, and suitable for scenarios like logging, serialization, MQL5 usage, and date/time formatting.
int64_t, double) like ts_t, fts_t for timestamps — easy to serialize and store.<cstdint>.NtpClient) are isolated and optional.DateTime value type storing UTC milliseconds with a fixed offset for ISO8601 round-trips, local/UTC components, arithmetic, and boundariesCompile-time macros in time_shield/core/config.hpp allow adapting the library to the target platform and toggling optional modules:
TIME_SHIELD_PLATFORM_WINDOWS / TIME_SHIELD_PLATFORM_UNIX — platform detection.TIME_SHIELD_HAS_WINSOCK — WinSock availability.TIME_SHIELD_ENABLE_NTP_CLIENT — builds the NTP client when set to 1.TIME_SHIELD_ENABLE_LEGACY_ALIASES enables compatibility aliases for confirmed renamed conversion helpers when defined before including Time Shield headers.The public API uses three stability tiers:
Short or alternative names are not legacy merely because a canonical equivalent exists. Legacy status requires repository history, documentation, an explicit rename, or an established replacement.
All public symbols are declared inside the time_shield namespace.
Public headers are grouped by domain. The preferred entry points are time_shield/core.hpp, time_shield/conversions.hpp, time_shield/text.hpp, time_shield/date_time.hpp, time_shield/timezone.hpp, time_shield/astronomy.hpp, time_shield/timers.hpp, and the optional time_shield/ntp.hpp. Domain paths are the supported public header paths.
ts_t represents Unix time in seconds as a signed 64-bit integer with microsecond precision available through conversions.fts_t stores time as double precision seconds; conversions maintain microsecond accuracy.dse, dse_ms, dse_to_ts, and dse_to_ts_ms provide concise aliases for days-since-epoch conversions.std::string rely on the caller for allocations.Here is a simple demonstration:
Additional example files are located in the examples/ folder:
time_utils_example.cpp — get timestamps and partstime_formatting_example.cpp — to_string, ISO8601, MQL5time_formatting_showcase_example.cpp — broader formatter showcase with UTC/local, ms, MQL5, human-readable, and filename helperstime_parser_example.cpp — parse ISO8601 and custom format stringsdate_time_example.cpp — fixed-offset DateTime parsing, formatting, and arithmetic helperstime_conversions_example.cpp — convert between formatstime_zone_conversions_example.cpp — GMT/UTC, Kyiv, IST/MYT, and generic zone-to-zone conversionsntp_client_example.cpp — NTP sync (sockets)Also see ntp_time_service_example.cpp for a compact wrapper-based NTP service example.
time_formatting_example.cpp shows ISO8601 formatting, custom formatting, offset-aware rendering, and filename-safe strings.
time_formatting_showcase_example.cpp shows a broader formatter cookbook with UTC/local variants, millisecond helpers, MQL5 output, human-readable strings, and filename-oriented helpers.
time_parser_example.cpp shows ISO8601 parsing, seconds/ms/floating timestamp parsing, formatter-compatible custom formats, and a simple failure case.
For stateless monotonic timing, use monotonic_sec(), monotonic_ms(), or monotonic_us(). These helpers return process-local monotonic counters for intervals and timeout logic rather than UTC timestamps.
ISO 8601 parsing uses a manual fast path without std::regex. Explicit timezone offsets are interpreted canonically: the wall-clock time in the string is converted to the corresponding UTC instant. For formatter-compatible custom patterns, use try_parse_format(), try_parse_format_ts(), or try_parse_format_ts_ms().
ISO week-date helpers convert between calendar dates and IsoWeekDateStruct, format ISO week dates, and parse canonical forms (YYYY-Www-D, YYYYWwwD) plus compatible mixed separator variants (YYYY-WwwD, YYYYWww-D). Parsing accepts uppercase or lowercase W, and omitted ISO weekday defaults to Monday. Formatter-compatible custom patterns also support G, g, V, and u for ISO week-based year, two-digit week-based year, week number, and ISO weekday. Custom parse formats reject mixes of ISO week-based year/week tokens with Gregorian Y, m, and d date tokens.
Time Shield provides an optional NTP stack (TIME_SHIELD_ENABLE_NTP_CLIENT) that can query remote servers and compute a local offset for UTC time.
NtpClient performs a single NTP request to one server.NtpClientPool samples multiple servers with rate limiting and backoff.NtpClientPoolRunner runs the pool periodically in a background thread.NtpTimeService exposes a singleton interface with cached offset/UTC time.Each response is parsed using the standard four-timestamp method: offset = ((t2 - t1) + (t3 - t4)) / 2, delay = (t4 - t1) - (t3 - t2), where t1 is client transmit, t2 is server receive, t3 is server transmit, and t4 is client receive time. Pool aggregation uses median or best-delay selection with optional MAD trimming and exponential smoothing.
NtpTimeService is header-only and supports C++11/C++14/C++17. The service uses an immortal singleton to avoid static destruction order issues. During normal runtime the singleton getters keep their lazy-start behavior. During process teardown the service does not restart background work and falls back to realtime plus the last cached offset. In general, C++17+ allows a simpler singleton-storage pattern with inline variables. For NtpTimeService, the public usage contract is the same in C++11/C++14/C++17.
Convert between Unix timestamps and Excel/COM OA dates, or derive basic astronomical values from calendar inputs:
The MoonPhaseCalculator class (time_shield::astronomy::MoonPhase) builds on these helpers to return illumination, distances, phase angles, continuous sin/cos for the phase, quarter instants, and “event windows” around new/full/quarter phases. Calculations are geocentric (no observer latitude/longitude or parallax corrections). Phase and illumination are therefore global for a given moment; what changes locally are timezone-adjusted date/time, the apparent orientation of the lit part (flipped between hemispheres), and visibility, which depends on horizon/atmosphere.
Basic class usage for bespoke calculations:
Check whether a moment falls on a business day using timestamps, calendar components, or ISO8601 strings:
Locate the first and last trading days for a month and constrain schedules to the opening or closing workdays:
The string overloads recognise the same ISO8601 formats handled by str_to_ts and str_to_ts_ms.
Locate the boundaries of the first and last workdays when preparing trading windows or settlement cutoffs:
These helpers follow the same semantics as start_of_day and end_of_day, returning UTC timestamps. Invalid month inputs or months without workdays yield ERROR_TIMESTAMP to simplify validation.
find_packageAfter installing the library (e.g., via cmake --install), locate it with find_package:
For header-only integration rules, multi-static-library usage, and Windows NTP linking details, see docs/library-integration-guidelines.md in the repository.
add_subdirectoryVendor the library as a submodule:
Then include it:
Install via a local overlay port:
Use the vcpkg toolchain when configuring CMake:
The port is intended to be upstreamed to microsoft/vcpkg.
For MQL5/MetaTrader, run install_mql5.bat to copy the .mqh files to your include directory.
To build the C++ examples use the helper scripts:
build-examples.bat for Windowsbuild_examples.sh for Linux/macOSbuild-cb.bat to generate a Code::Blocks project| Platform | Compilers | C++ Standards |
|---|---|---|
| Windows | MSVC, ClangCL | 11, 14, 17 |
| Linux | GCC, Clang | 11, 14, 17 |
| macOS | Apple Clang | 11, 14, 17 |
The latest generated API reference is available at liminode.github.io/time-shield-cpp. Russian engineering guides are available in the repository: header implementation, library integration, and singleton storage.
Time Shield Library GitHub repository
This library is licensed under the MIT License. See the LICENSE file for more details.