Date and Time
DateTime class
-
class DateTime
Date and time class.
This class contains a ‘broken-down’ date and time into its individual year, month, etc. components.
Date and time functions mostly work with Unix time, the quantity of seconds since 00:00:00 1970-01-01. There is no support for leap seconds which are added (and in theory, removed) occasionally to compensate for earth rotation variation. This means that timespan calculation and free-running clocks may be inaccurate if they span leap seconds. To facilitate leap seconds, reference must be made to leap second table. This will not be done within the Sming framework and must be handled by application code if required.
32-bit signed values support a range of +/-68 years; the Unix epoch is midnight 1 Jan 1970, so overflows at about 3am on 19 Jan 2038. The value is signed which allows dates prior to 1970 to be represented.
An unsigned 32-bit value can be used to store dates provided they are after 1970. These are good until February 2106.
Note
time_t is a signed 64-bit value for all architectures except Windows Host and esp32 ESP-IDF 4.x.
Public Functions
-
DateTime() = default
Instantiate an uninitialised date and time object.
-
inline DateTime(time_t time)
Instantiate a date and time object from a Unix timestamp.
- Parameters:
time – Unix time to assign to object
-
inline operator time_t()
Get current Unix time.
- Return values:
time_t – Quantity of seconds since 00:00:00 1970-01-01
-
void setTime(time_t time)
Set time using Unix timestamp.
- Parameters:
time – Unix time to set object time to
-
inline void setTime(uint8_t sec, uint8_t min, uint8_t hour, uint8_t day, uint8_t month, uint16_t year)
Set time using time and date component values.
- Parameters:
sec – Seconds
min – Minutes
hour – Hour
day – Day of month
month – Month (0=Jan, 11=Dec)
year – Year
-
bool fromHttpDate(const String &httpDate)
Parse a HTTP full date and set time and date.
See also
See
fromHttpDate(const String& time_t&)
- Parameters:
httpDate – HTTP full date in RFC 1123 format, e.g. Sun, 06 Nov 1994 08:49:37 GMT
- Return values:
bool – True on success
-
bool fromISO8601(const String &datetime, ZoneInfo *zone = nullptr)
Parse an ISO8601 date/time string.
- Parameters:
datetime – Date and optional time in ISO8601 format, e.g. “1994-11-06”, “1994-11-06T08:49:37”. Separators are optional.
zone – If provided, on success the
offsetMins
field will contain the time offset (0 for GMT) and the decoded DateTime will be ‘local’. If zone is null then the decoded datetime will be UTC.
- Return values:
bool – True on success. On failure, value of DateTime is unchanged.
-
bool isNull() const
Check if time date object is initialised.
- Return values:
True – if object has no value. False if initialised.
-
time_t toUnixTime() const
Get Unix time.
Note
Unix time does not account for leap seconds.
- Return values:
time_t – Unix time, quantity of seconds since 00:00:00 1970-01-01
-
String toShortDateString() const
Get human readable date.
- Return values:
String – Date in requested format, e.g. DD.MM.YYYY
-
String toShortTimeString(bool includeSeconds = false) const
Get human readable time.
- Parameters:
includeSeconds – True to include seconds (Default: false)
- Return values:
String – Time in format hh:mm or hh:mm:ss
-
String toFullDateTimeString() const
Get human readable date and time.
- Return values:
String – Date and time in format DD.MM.YYYY hh:mm:ss
-
String toISO8601(const ZoneInfo *zone = nullptr) const
Get human readable date and time.
See also
See
fromISO8601()
for string formatsNote
If
zone
isn’t specified then UTC is assumed and timezone indicator ‘Z’ will be appended- Parameters:
zone – Optional timezone information
- Return values:
String – Date and time
-
String toHTTPDate() const
Get human readable date and time.
- Return values:
String – Date and time in format DDD, DD MMM YYYY hh:mm:ss GMT
-
void addMilliseconds(long add)
Add time to date time object.
Note
This operation is computationally expensive, requiring conversion to and from time_t.
- Parameters:
add – Quantity of milliseconds to add to object
-
String format(const char *formatString, const ZoneInfo *zone = nullptr) const
Create string formatted with time and date placeholders.
(1) If zone is not provided then the z, %:z and Z placeholders produce empty text
Note
Uses strftime style formatting, e.g. format(“Today is %a, %d %b %Y”) returns “Today is Mon, 10 Dec 2018”
Note
Localisation may be implemented in libsming at compile time by setting LOCALE, e.g. LOCALE=LOCALE_DE_DE
Note
Default localisation is EN_GB
Note
Formatting parameters
Param
Description
Locale
%a
Abbreviated weekday name
*
%A
Full weekday name
*
%b
Abbreviated month name
*
%B
Full month name
*
%c
Locale preferred date and time format
*
%C
Century number (2 digits)
%d
Day of month as decimal number with leading zero (2 digits)
%D
US date format (mm/dd/yyyy)
%e
Day of month as decimal number with leading space (2 digits)
%F
ISO 8601 date format (YYYY-mm-dd)
%h
Equivalent to %b
*
%H
Hour as a decimal number using a 24-hour clock (range 00 to 23)
%I
Hour as a decimal number using a 12-hour clock (range 00 to 12)
%j
Day of the year as a decimal number (range 001 to 366)
%m
Month as a decimal number (range 01 to 12)
%M
Minute as a decimal number (range 00 to 59)
%n
Newline
%p
Meridiem indicator: AM or PM. Midnight is AM and noon is PM
%r
Locale 12-hour clock time notation. This is equivalent to %I:%M:%S %p
*
%R
Time in 24-hour notation (HH:MM)
%S
Second as a decimal number (range 00 to 60)
%t
Horizontal tab
%T
Time in 24-hour notation (HH:MM:SS)
%u
Day of the week as a decimal (range 1 to 7, Monday is 1)
%U
Week number as a decimal number (range 00 to 53, first Sunday as the first day of week 01)
%V
ISO 8601 week number as a decimal number (range 01 to 53, where week 1 is the first week including a Thursday)
%w
Day of the week as a decimal (range 0 to 6, Sunday is 0)
%W
Week number as a decimal number (range 00 to 53, first Monday as the first day of week 01)
%x
Locale preferred date representation
*
%X
Locale preferred time representation
*
%y
Year as a decimal number without a century (range 00 to 99)
%Y
Year as a decimal number (range 1970 to …)
%z
Timezone offset in ±HHMM format (1)
%%:z
Timezone offset in ±HH:MM format (1)
%Z
Timezone tag (1)
%%
Percent sign
- Parameters:
formatString – String including date and time formatting
zone – Optional timezone information
- Return values:
String – Formatted string
-
inline String format(const String &formatString, const ZoneInfo *zone = nullptr) const
Create string formatted with time and date placeholders.
See also
See
format(const char*, const ZoneInfo*)
for parameter details- Parameters:
formatString – String including date and time formatting
zone – Optional zone information containing additional format information
- Return values:
String – Formatted string
Public Members
-
uint16_t Year = 0
Full Year number.
-
uint16_t DayofYear = 0
Day of year (0-365)
-
uint8_t DayofWeek = 0
Day of week (0-6 Sunday is day 0)
-
uint8_t Month = 0
Month (0-11 Jan is month 0)
-
uint8_t Day = 0
Day of month (1-31)
-
uint8_t Hour = 0
Hour (0-23)
-
uint8_t Minute = 0
Minute (0-59)
-
uint8_t Second = 0
Second (0-59)
-
uint16_t Milliseconds = 0
Milliseconds (0-999)
Public Static Functions
-
static bool fromHttpDate(const String &httpDate, time_t &time)
Parse a HTTP full date string and return the time_t value.
Note
Also supports obsolete RFC 850 date format, e.g. Sunday, 06-Nov-94 08:49:37 GMT where 2 digit year represents range 1970-2069
Note
GMT suffix is optional and is always assumed / ignored
- Parameters:
httpDate – HTTP full date in RFC 1123 format, e.g. Sun, 06 Nov 1994 08:49:37 GMT
time – On success, contains the decoded value
- Return values:
bool – True on success
-
static bool fromISO8601(const String &datetime, time_t &time, uint16_t &milliseconds, int16_t &offsetMins)
Parse an ISO8601 date/time string and return discrete components.
Basic format
doesn’t include separators, whereasExtended format
does. Both are supported.See also
Acceptable date formats:
Acceptable time formats:YYYY-MM-DD or YYYYMMDD YYYY-MM (but not YYYYMM)
Times with an offset:Thh:mm:ss.sss or Thhmmss.sss Thh:mm:ss or Thhmmss Thh:mm.mmm or Thhmm.mmm Thh:mm or Thhmm Thh.hhh Thh
<time>Z <time>±hh:mm <time>±hhmm <time>±hh
- Parameters:
datetime – Date and optional time in ISO8601 format, e.g. “1994-11-06”, “1994-11-06T08:49:37”. Separators are optional.
time – The time_t component
milliseconds – Additional milliseconds value
offsetMins – Any offset specified in the time
- Return values:
bool – True on success
-
static void fromUnixTime(time_t timep, uint8_t *psec, uint8_t *pmin, uint8_t *phour, uint8_t *pday, uint8_t *pwday, uint8_t *pmonth, uint16_t *pyear)
Convert from Unix time to individual time components.
Note
Pass the Unix timedate value and pointers to existing integers. The integers are updated with the converted values
Note
This static function may be used without instantiating a DateTime object, e.g. DateTime::convertFromUnixTime(…);
Note
Unix time does not account for leap seconds.
Note
All of the return values are optional, specify nullptr if not required
- Parameters:
timep – Unix time date value to convert
psec – Pointer to integer to hold resulting seconds
pmin – Pointer to integer to hold resulting minutes
phour – Pointer to integer to hold resulting hour
pday – Pointer to integer to hold resulting day of month
pwday – Pointer to integer to hold resulting day of week
pmonth – Pointer to integer to hold resulting month
pyear – Pointer to integer to hold resulting year
-
static time_t toUnixTime(int sec, int min, int hour, int day, uint8_t month, uint16_t year)
Convert from individual time components to Unix time.
Note
Seconds, minutes, hours and days may be any value, e.g. to calculate the value for 300 days since 1970 (epoch), set day=300
Note
This static function may be used without instantiating a DateTime object, e.g.
time_t unixTime = DateTime::toUnixTime(...);
Note
Unix time does not account for leap seconds.
- Parameters:
sec – Seconds
min – Minutes
hour – Hours
day – Days
month – Month (0-11, Jan=0, Feb=1, …Dec=11), or enum (dtJanuary, …)
year – Year, either full 4 digit year or 2 digits for 2000-2068
- Return values:
time_t – Number of seconds since unix epoch (Midnight, Jan 1 1970)
-
struct ZoneInfo
Basic information required when displaying or handling local times.
Public Functions
-
inline int offsetSecs() const
Get the offset in seconds so it can be added/subtracted directly from a time_t value.
Public Members
-
int16_t offsetMins = {0}
Offset from UTC in minutes.
-
bool isDst = {false}
True if daylight savings is in effect.
-
struct Tag
Type for timezone abbreviation such as “GMT”, “EEST”.
-
inline int offsetSecs() const
-
DateTime() = default
ZonedTime class
-
class ZonedTime
A timestamp representing a UTC ‘point in time’ associated with a specific timezone.
Derivation of the correct
DateTime::ZoneInfo
value is complex and typically managed by an external library, such as :library:Timezone
.The implicit
time_t
value for a ZonedTime is the corresponding UTC time. All comparisons or arithmetic operations will therefore operate using this value. This means two ZonedTime objects will be considered equal if their corresponding UTC timestamps match, even if they derive from different timezones.To obtain the
time_t
value with local offset applied, uselocal()
:There is no support in this class for manipulating time or zone information directly. This should be done using the rawDateTime dtLocal(zonedTime.local());
time_t
value and a new ZonedTime object constructed.Format time using <tt>DateTime</tt>
See also
See
DateTime::format()
for detailsPublic Functions
-
inline ZonedTime(time_t utc, const DateTime::ZoneInfo &zoneInfo)
Construct a zoned time.
- Parameters:
utc –
zoneInfo –
-
inline explicit ZonedTime(time_t utc = 0)
Construct a time in the UTC zone.
-
inline ZonedTime toUtc() const
Get a ZonedTime instance translated into the UTC zone This does nothing more than replace the contained zone information with UTC, which has tag “UTC”, no offset and no daylight savings.
-
inline time_t local() const
Obtain the
time_t
value adjusted for local time.
-
inline ZonedTime(time_t utc, const DateTime::ZoneInfo &zoneInfo)
System Clock
Enums
Variables
-
SystemClockClass SystemClock
Global instance of system clock object.
Note
Use SystemClock.function to access system clock functions
Note
Example:
SystemClock.setTimeZone(+9.5); //Darwin, Australia
-
class SystemClockClass
- #include <SystemClock.h>
Public Types
-
using CheckTimeZoneOffset = Delegate<void(time_t systemTime)>
Optional callback which can be used to automate handling of timezone changes.
Although the timezone offset only changes twice a year, when it does change the corresponding offset should be updated promptly.
setTimeZoneOffset()
is typically called when updating via real-time clock chip or NTP, but this can still leave a considerable gap during which the local time will be wrong.The callback should check the provided systemTime and determine if the time zone offset requires changing and, if so, call
setTimeZoneOffset()
. One way to make this efficient is to cache thetime_t
value for the next change, rather than attemtpting to compute the offset on every call.- Param systemTime:
The current system time
Public Functions
-
time_t now(TimeZone timeType = eTZ_Local) const
Get the current date and time.
- Parameters:
timeType – Time zone to use (UTC / local)
- Return values:
DateTime – Current date and time
-
bool setTime(time_t time, TimeZone timeType)
Set the system clock’s time.
Note
System time is always stored as UTC time. If setting using the value retrieved from a time server using NTP, specify eTZ_UTC. If passing a local value using eTZ_Local, ensure that the time zone has been set correctly as it will be converted to UTC before storing.
- Parameters:
time – Unix time to set clock to (quantity of seconds since 00:00:00 1970-01-01)
timeType – Time zone of Unix time, i.e. is time provided as local or UTC?
-
String getSystemTimeString(TimeZone timeType = eTZ_Local) const
Get current time as a string.
- Parameters:
timeType – Time zone to present time as, i.e. return local or UTC time
- Return values:
String – Current time in format:
dd.mm.yy hh:mm:ss
-
inline void setTimeZoneOffset(int seconds)
Sets the local time zone offset.
See also
See
setTimeZone()
.- Parameters:
seconds – Offset from UTC of local time zone in seconds
-
inline void setTimeZone(float localTimezoneOffset)
Set the local time zone offset in hours.
Note
Values for local standard time may exceed +/- 12 For example, Pacific/Kiritimati has a 14-hour offset (in 2024).
- Parameters:
localTimezoneOffset – Offset from UTC of local time zone in hours
- Return values:
bool – true on success, false if value out of range
-
inline void setTimeZone(const DateTime::ZoneInfo &zoneInfo)
Set current time zone information.
- Parameters:
zoneInfo – Contains offset plus string formatting information
-
inline const DateTime::ZoneInfo &getTimeZone() const
Get current time zone information.
- Return values:
ZoneInfo –
-
inline int getTimeZoneOffset() const
Get the current time zone offset.
- Return values:
int – Offset in seconds from UTC
-
inline bool isSet() const
Determine if
setTime()
has been called yet.Note
Indicates whether time returned can be relied upon
-
inline void onCheckTimeZoneOffset(CheckTimeZoneOffset callback)
Set/clear a callback which is invoked whenever local time is queried.
Note
This callback is only invoked when
now()
is called.
-
using CheckTimeZoneOffset = Delegate<void(time_t systemTime)>