[3.x] Add a Time singleton

This commit is contained in:
Aaron Franke 2021-10-20 22:14:41 -05:00
parent 964c6ec4d9
commit 035a84fe92
No known key found for this signature in database
GPG Key ID: 40A1750B977E56BF
7 changed files with 798 additions and 0 deletions

433
core/os/time.cpp Normal file
View File

@ -0,0 +1,433 @@
/*************************************************************************/
/* time.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "time.h"
#include "core/os/os.h"
#define UNIX_EPOCH_YEAR_AD 1970 // 1970
#define SECONDS_PER_DAY (24 * 60 * 60) // 86400
#define IS_LEAP_YEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
#define YEAR_SIZE(year) (IS_LEAP_YEAR(year) ? 366 : 365)
#define YEAR_KEY "year"
#define MONTH_KEY "month"
#define DAY_KEY "day"
#define WEEKDAY_KEY "weekday"
#define HOUR_KEY "hour"
#define MINUTE_KEY "minute"
#define SECOND_KEY "second"
#define DST_KEY "dst"
// Table of number of days in each month (for regular year and leap year).
static const uint8_t MONTH_DAYS_TABLE[2][12] = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};
VARIANT_ENUM_CAST(Time::Month);
VARIANT_ENUM_CAST(Time::Weekday);
#define UNIX_TIME_TO_HMS \
uint8_t hour, minute, second; \
{ \
/* The time of the day (in seconds since start of day). */ \
uint32_t day_clock = Math::posmod(p_unix_time_val, SECONDS_PER_DAY); \
/* On x86 these 4 lines can be optimized to only 2 divisions. */ \
second = day_clock % 60; \
day_clock /= 60; \
minute = day_clock % 60; \
hour = day_clock / 60; \
}
#define UNIX_TIME_TO_YMD \
int64_t year; \
Month month; \
uint8_t day; \
/* The day number since Unix epoch (0-index). Days before 1970 are negative. */ \
int64_t day_number = Math::floor(p_unix_time_val / (double)SECONDS_PER_DAY); \
{ \
int64_t day_number_copy = day_number; \
year = UNIX_EPOCH_YEAR_AD; \
uint8_t month_zero_index = 0; \
while (day_number_copy >= YEAR_SIZE(year)) { \
day_number_copy -= YEAR_SIZE(year); \
year++; \
} \
while (day_number_copy < 0) { \
year--; \
day_number_copy += YEAR_SIZE(year); \
} \
/* After the above, day_number now represents the day of the year (0-index). */ \
while (day_number_copy >= MONTH_DAYS_TABLE[IS_LEAP_YEAR(year)][month_zero_index]) { \
day_number_copy -= MONTH_DAYS_TABLE[IS_LEAP_YEAR(year)][month_zero_index]; \
month_zero_index++; \
} \
/* After the above, day_number now represents the day of the month (0-index). */ \
month = (Month)(month_zero_index + 1); \
day = day_number_copy + 1; \
}
#define VALIDATE_YMDHMS \
ERR_FAIL_COND_V_MSG(month == 0, 0, "Invalid month value of: " + itos(month) + ", months are 1-indexed and cannot be 0. See the Time.Month enum for valid values."); \
ERR_FAIL_COND_V_MSG(month > 12, 0, "Invalid month value of: " + itos(month) + ". See the Time.Month enum for valid values."); \
ERR_FAIL_COND_V_MSG(hour > 23, 0, "Invalid hour value of: " + itos(hour) + "."); \
ERR_FAIL_COND_V_MSG(minute > 59, 0, "Invalid minute value of: " + itos(minute) + "."); \
ERR_FAIL_COND_V_MSG(second > 59, 0, "Invalid second value of: " + itos(second) + " (leap seconds are not supported)."); \
/* Do this check after month is tested as valid. */ \
ERR_FAIL_COND_V_MSG(day == 0, 0, "Invalid day value of: " + itos(month) + ", days are 1-indexed and cannot be 0."); \
uint8_t days_in_this_month = MONTH_DAYS_TABLE[IS_LEAP_YEAR(year)][month - 1]; \
ERR_FAIL_COND_V_MSG(day > days_in_this_month, 0, "Invalid day value of: " + itos(day) + " which is larger than the maximum for this month, " + itos(days_in_this_month) + ".");
#define YMD_TO_DAY_NUMBER \
/* The day number since Unix epoch (0-index). Days before 1970 are negative. */ \
int64_t day_number = day - 1; \
/* Add the days in the months to day_number. */ \
for (int i = 0; i < month - 1; i++) { \
day_number += MONTH_DAYS_TABLE[IS_LEAP_YEAR(year)][i]; \
} \
/* Add the days in the years to day_number. */ \
if (year >= UNIX_EPOCH_YEAR_AD) { \
for (int64_t iyear = UNIX_EPOCH_YEAR_AD; iyear < year; iyear++) { \
day_number += YEAR_SIZE(iyear); \
} \
} else { \
for (int64_t iyear = UNIX_EPOCH_YEAR_AD - 1; iyear >= year; iyear--) { \
day_number -= YEAR_SIZE(iyear); \
} \
}
#define PARSE_ISO8601_STRING \
int64_t year = UNIX_EPOCH_YEAR_AD; \
Month month = MONTH_JANUARY; \
uint8_t day = 1; \
uint8_t hour = 0; \
uint8_t minute = 0; \
uint8_t second = 0; \
{ \
bool has_date = false, has_time = false; \
String date, time; \
if (p_datetime.find_char('T') > 0) { \
has_date = has_time = true; \
Vector<String> array = p_datetime.split("T"); \
date = array[0]; \
time = array[1]; \
} else if (p_datetime.find_char(' ') > 0) { \
has_date = has_time = true; \
Vector<String> array = p_datetime.split(" "); \
date = array[0]; \
time = array[1]; \
} else if (p_datetime.find_char('-', 1) > 0) { \
has_date = true; \
date = p_datetime; \
} else if (p_datetime.find_char(':') > 0) { \
has_time = true; \
time = p_datetime; \
} \
/* Set the variables from the contents of the string. */ \
if (has_date) { \
Vector<int> array = date.split_ints("-", false); \
year = array[0]; \
month = (Month)array[1]; \
day = array[2]; \
/* Handle negative years. */ \
if (p_datetime.find_char('-') == 0) { \
year *= -1; \
} \
} \
if (has_time) { \
Vector<int> array = time.split_ints(":", false); \
hour = array[0]; \
minute = array[1]; \
second = array[2]; \
} \
}
#define EXTRACT_FROM_DICTIONARY \
/* Get all time values from the dictionary. If it doesn't exist, set the */ \
/* values to the default values for Unix epoch (1970-01-01 00:00:00). */ \
int64_t year = p_datetime.has(YEAR_KEY) ? int64_t(p_datetime[YEAR_KEY]) : UNIX_EPOCH_YEAR_AD; \
Month month = Month((p_datetime.has(MONTH_KEY)) ? uint8_t(p_datetime[MONTH_KEY]) : 1); \
uint8_t day = p_datetime.has(DAY_KEY) ? uint8_t(p_datetime[DAY_KEY]) : 1; \
uint8_t hour = p_datetime.has(HOUR_KEY) ? uint8_t(p_datetime[HOUR_KEY]) : 0; \
uint8_t minute = p_datetime.has(MINUTE_KEY) ? uint8_t(p_datetime[MINUTE_KEY]) : 0; \
uint8_t second = p_datetime.has(SECOND_KEY) ? uint8_t(p_datetime[SECOND_KEY]) : 0;
Time *Time::singleton = nullptr;
Time *Time::get_singleton() {
if (!singleton) {
memnew(Time);
}
return singleton;
}
Dictionary Time::get_datetime_dict_from_unix_time(int64_t p_unix_time_val) const {
UNIX_TIME_TO_HMS
UNIX_TIME_TO_YMD
Dictionary datetime;
datetime[YEAR_KEY] = year;
datetime[MONTH_KEY] = (uint8_t)month;
datetime[DAY_KEY] = day;
// Unix epoch was a Thursday (day 0 aka 1970-01-01).
datetime[WEEKDAY_KEY] = Math::posmod(day_number + WEEKDAY_THURSDAY, 7);
datetime[HOUR_KEY] = hour;
datetime[MINUTE_KEY] = minute;
datetime[SECOND_KEY] = second;
return datetime;
}
Dictionary Time::get_date_dict_from_unix_time(int64_t p_unix_time_val) const {
UNIX_TIME_TO_YMD
Dictionary datetime;
datetime[YEAR_KEY] = year;
datetime[MONTH_KEY] = (uint8_t)month;
datetime[DAY_KEY] = day;
// Unix epoch was a Thursday (day 0 aka 1970-01-01).
datetime[WEEKDAY_KEY] = Math::posmod(day_number + WEEKDAY_THURSDAY, 7);
return datetime;
}
Dictionary Time::get_time_dict_from_unix_time(int64_t p_unix_time_val) const {
UNIX_TIME_TO_HMS
Dictionary datetime;
datetime[HOUR_KEY] = hour;
datetime[MINUTE_KEY] = minute;
datetime[SECOND_KEY] = second;
return datetime;
}
String Time::get_datetime_string_from_unix_time(int64_t p_unix_time_val, bool p_use_space) const {
UNIX_TIME_TO_HMS
UNIX_TIME_TO_YMD
// vformat only supports up to 6 arguments, so we need to split this up into 2 parts.
String timestamp = vformat("%04d-%02d-%02d", year, (uint8_t)month, day);
if (p_use_space) {
timestamp = vformat("%s %02d:%02d:%02d", timestamp, hour, minute, second);
} else {
timestamp = vformat("%sT%02d:%02d:%02d", timestamp, hour, minute, second);
}
return timestamp;
}
String Time::get_date_string_from_unix_time(int64_t p_unix_time_val) const {
UNIX_TIME_TO_YMD
// Android is picky about the types passed to make Variant, so we need a cast.
return vformat("%04d-%02d-%02d", year, (uint8_t)month, day);
}
String Time::get_time_string_from_unix_time(int64_t p_unix_time_val) const {
UNIX_TIME_TO_HMS
return vformat("%02d:%02d:%02d", hour, minute, second);
}
Dictionary Time::get_datetime_dict_from_string(String p_datetime, bool p_weekday) const {
PARSE_ISO8601_STRING
Dictionary dict;
dict[YEAR_KEY] = year;
dict[MONTH_KEY] = (uint8_t)month;
dict[DAY_KEY] = day;
if (p_weekday) {
YMD_TO_DAY_NUMBER
// Unix epoch was a Thursday (day 0 aka 1970-01-01).
dict[WEEKDAY_KEY] = Math::posmod(day_number + WEEKDAY_THURSDAY, 7);
}
dict[HOUR_KEY] = hour;
dict[MINUTE_KEY] = minute;
dict[SECOND_KEY] = second;
return dict;
}
String Time::get_datetime_string_from_dict(Dictionary p_datetime, bool p_use_space) const {
ERR_FAIL_COND_V_MSG(p_datetime.empty(), "", "Invalid datetime Dictionary: Dictionary is empty.");
EXTRACT_FROM_DICTIONARY
// vformat only supports up to 6 arguments, so we need to split this up into 2 parts.
String timestamp = vformat("%04d-%02d-%02d", year, (uint8_t)month, day);
if (p_use_space) {
timestamp = vformat("%s %02d:%02d:%02d", timestamp, hour, minute, second);
} else {
timestamp = vformat("%sT%02d:%02d:%02d", timestamp, hour, minute, second);
}
return timestamp;
}
int64_t Time::get_unix_time_from_datetime_dict(Dictionary p_datetime) const {
ERR_FAIL_COND_V_MSG(p_datetime.empty(), 0, "Invalid datetime Dictionary: Dictionary is empty");
EXTRACT_FROM_DICTIONARY
VALIDATE_YMDHMS
YMD_TO_DAY_NUMBER
return day_number * SECONDS_PER_DAY + hour * 3600 + minute * 60 + second;
}
int64_t Time::get_unix_time_from_datetime_string(String p_datetime) const {
PARSE_ISO8601_STRING
VALIDATE_YMDHMS
YMD_TO_DAY_NUMBER
return day_number * SECONDS_PER_DAY + hour * 3600 + minute * 60 + second;
}
Dictionary Time::get_datetime_dict_from_system(bool p_utc) const {
OS::Date date = OS::get_singleton()->get_date(p_utc);
OS::Time time = OS::get_singleton()->get_time(p_utc);
Dictionary datetime;
datetime[YEAR_KEY] = date.year;
datetime[MONTH_KEY] = (uint8_t)date.month;
datetime[DAY_KEY] = date.day;
datetime[WEEKDAY_KEY] = (uint8_t)date.weekday;
datetime[DST_KEY] = date.dst;
datetime[HOUR_KEY] = time.hour;
datetime[MINUTE_KEY] = time.min;
datetime[SECOND_KEY] = time.sec;
return datetime;
}
Dictionary Time::get_date_dict_from_system(bool p_utc) const {
OS::Date date = OS::get_singleton()->get_date(p_utc);
Dictionary date_dictionary;
date_dictionary[YEAR_KEY] = date.year;
date_dictionary[MONTH_KEY] = (uint8_t)date.month;
date_dictionary[DAY_KEY] = date.day;
date_dictionary[WEEKDAY_KEY] = (uint8_t)date.weekday;
date_dictionary[DST_KEY] = date.dst;
return date_dictionary;
}
Dictionary Time::get_time_dict_from_system(bool p_utc) const {
OS::Time time = OS::get_singleton()->get_time(p_utc);
Dictionary time_dictionary;
time_dictionary[HOUR_KEY] = time.hour;
time_dictionary[MINUTE_KEY] = time.min;
time_dictionary[SECOND_KEY] = time.sec;
return time_dictionary;
}
String Time::get_datetime_string_from_system(bool p_utc, bool p_use_space) const {
OS::Date date = OS::get_singleton()->get_date(p_utc);
OS::Time time = OS::get_singleton()->get_time(p_utc);
// vformat only supports up to 6 arguments, so we need to split this up into 2 parts.
String timestamp = vformat("%04d-%02d-%02d", date.year, (uint8_t)date.month, date.day);
if (p_use_space) {
timestamp = vformat("%s %02d:%02d:%02d", timestamp, time.hour, time.min, time.sec);
} else {
timestamp = vformat("%sT%02d:%02d:%02d", timestamp, time.hour, time.min, time.sec);
}
return timestamp;
}
String Time::get_date_string_from_system(bool p_utc) const {
OS::Date date = OS::get_singleton()->get_date(p_utc);
// Android is picky about the types passed to make Variant, so we need a cast.
return vformat("%04d-%02d-%02d", date.year, (uint8_t)date.month, date.day);
}
String Time::get_time_string_from_system(bool p_utc) const {
OS::Time time = OS::get_singleton()->get_time(p_utc);
return vformat("%02d:%02d:%02d", time.hour, time.min, time.sec);
}
Dictionary Time::get_time_zone_from_system() const {
OS::TimeZoneInfo info = OS::get_singleton()->get_time_zone_info();
Dictionary timezone;
timezone["bias"] = info.bias;
timezone["name"] = info.name;
return timezone;
}
double Time::get_unix_time_from_system() const {
return OS::get_singleton()->get_unix_time();
}
uint64_t Time::get_ticks_msec() const {
return OS::get_singleton()->get_ticks_msec();
}
uint64_t Time::get_ticks_usec() const {
return OS::get_singleton()->get_ticks_usec();
}
void Time::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_datetime_dict_from_unix_time", "unix_time_val"), &Time::get_datetime_dict_from_unix_time);
ClassDB::bind_method(D_METHOD("get_date_dict_from_unix_time", "unix_time_val"), &Time::get_date_dict_from_unix_time);
ClassDB::bind_method(D_METHOD("get_time_dict_from_unix_time", "unix_time_val"), &Time::get_time_dict_from_unix_time);
ClassDB::bind_method(D_METHOD("get_datetime_string_from_unix_time", "unix_time_val", "use_space"), &Time::get_datetime_string_from_unix_time, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_date_string_from_unix_time", "unix_time_val"), &Time::get_date_string_from_unix_time);
ClassDB::bind_method(D_METHOD("get_time_string_from_unix_time", "unix_time_val"), &Time::get_time_string_from_unix_time);
ClassDB::bind_method(D_METHOD("get_datetime_dict_from_string", "datetime", "weekday"), &Time::get_datetime_dict_from_string);
ClassDB::bind_method(D_METHOD("get_datetime_string_from_dict", "datetime", "use_space"), &Time::get_datetime_string_from_dict);
ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime_dict", "datetime"), &Time::get_unix_time_from_datetime_dict);
ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime_string", "datetime"), &Time::get_unix_time_from_datetime_string);
ClassDB::bind_method(D_METHOD("get_datetime_dict_from_system", "utc"), &Time::get_datetime_dict_from_system, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_date_dict_from_system", "utc"), &Time::get_date_dict_from_system, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_time_dict_from_system", "utc"), &Time::get_time_dict_from_system, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_datetime_string_from_system", "utc", "use_space"), &Time::get_datetime_string_from_system, DEFVAL(false), DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_date_string_from_system", "utc"), &Time::get_date_string_from_system, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_time_string_from_system", "utc"), &Time::get_time_string_from_system, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_time_zone_from_system"), &Time::get_time_zone_from_system);
ClassDB::bind_method(D_METHOD("get_unix_time_from_system"), &Time::get_unix_time_from_system);
ClassDB::bind_method(D_METHOD("get_ticks_msec"), &Time::get_ticks_msec);
ClassDB::bind_method(D_METHOD("get_ticks_usec"), &Time::get_ticks_usec);
BIND_ENUM_CONSTANT(MONTH_JANUARY);
BIND_ENUM_CONSTANT(MONTH_FEBRUARY);
BIND_ENUM_CONSTANT(MONTH_MARCH);
BIND_ENUM_CONSTANT(MONTH_APRIL);
BIND_ENUM_CONSTANT(MONTH_MAY);
BIND_ENUM_CONSTANT(MONTH_JUNE);
BIND_ENUM_CONSTANT(MONTH_JULY);
BIND_ENUM_CONSTANT(MONTH_AUGUST);
BIND_ENUM_CONSTANT(MONTH_SEPTEMBER);
BIND_ENUM_CONSTANT(MONTH_OCTOBER);
BIND_ENUM_CONSTANT(MONTH_NOVEMBER);
BIND_ENUM_CONSTANT(MONTH_DECEMBER);
BIND_ENUM_CONSTANT(WEEKDAY_SUNDAY);
BIND_ENUM_CONSTANT(WEEKDAY_MONDAY);
BIND_ENUM_CONSTANT(WEEKDAY_TUESDAY);
BIND_ENUM_CONSTANT(WEEKDAY_WEDNESDAY);
BIND_ENUM_CONSTANT(WEEKDAY_THURSDAY);
BIND_ENUM_CONSTANT(WEEKDAY_FRIDAY);
BIND_ENUM_CONSTANT(WEEKDAY_SATURDAY);
}
Time::Time() {
ERR_FAIL_COND_MSG(singleton, "Singleton for Time already exists.");
singleton = this;
}
Time::~Time() {
singleton = nullptr;
}

109
core/os/time.h Normal file
View File

@ -0,0 +1,109 @@
/*************************************************************************/
/* time.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef TIME_H
#define TIME_H
#include "core/class_db.h"
// This Time class conforms with as many of the ISO 8601 standards as possible.
// * As per ISO 8601:2004 4.3.2.1, all dates follow the Proleptic Gregorian
// calendar. As such, the day before 1582-10-15 is 1582-10-14, not 1582-10-04.
// See: https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar
// * As per ISO 8601:2004 3.4.2 and 4.1.2.4, the year before 1 AD (aka 1 BC)
// is number "0", with the year before that (2 BC) being "-1", etc.
// Conversion methods assume "the same timezone", and do not handle DST.
// Leap seconds are not handled, they must be done manually if desired.
// Suffixes such as "Z" are not handled, you need to strip them away manually.
class Time : public Object {
GDCLASS(Time, Object);
static void _bind_methods();
static Time *singleton;
public:
static Time *get_singleton();
enum Month : uint8_t {
/// Start at 1 to follow Windows SYSTEMTIME structure
/// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
MONTH_JANUARY = 1,
MONTH_FEBRUARY,
MONTH_MARCH,
MONTH_APRIL,
MONTH_MAY,
MONTH_JUNE,
MONTH_JULY,
MONTH_AUGUST,
MONTH_SEPTEMBER,
MONTH_OCTOBER,
MONTH_NOVEMBER,
MONTH_DECEMBER,
};
enum Weekday : uint8_t {
WEEKDAY_SUNDAY,
WEEKDAY_MONDAY,
WEEKDAY_TUESDAY,
WEEKDAY_WEDNESDAY,
WEEKDAY_THURSDAY,
WEEKDAY_FRIDAY,
WEEKDAY_SATURDAY,
};
// Methods that convert times.
Dictionary get_datetime_dict_from_unix_time(int64_t p_unix_time_val) const;
Dictionary get_date_dict_from_unix_time(int64_t p_unix_time_val) const;
Dictionary get_time_dict_from_unix_time(int64_t p_unix_time_val) const;
String get_datetime_string_from_unix_time(int64_t p_unix_time_val, bool p_use_space = false) const;
String get_date_string_from_unix_time(int64_t p_unix_time_val) const;
String get_time_string_from_unix_time(int64_t p_unix_time_val) const;
Dictionary get_datetime_dict_from_string(String p_datetime, bool p_weekday = true) const;
String get_datetime_string_from_dict(Dictionary p_datetime, bool p_use_space = false) const;
int64_t get_unix_time_from_datetime_dict(Dictionary p_datetime) const;
int64_t get_unix_time_from_datetime_string(String p_datetime) const;
// Methods that get information from OS.
Dictionary get_datetime_dict_from_system(bool p_utc = false) const;
Dictionary get_date_dict_from_system(bool p_utc = false) const;
Dictionary get_time_dict_from_system(bool p_utc = false) const;
String get_datetime_string_from_system(bool p_utc = false, bool p_use_space = false) const;
String get_date_string_from_system(bool p_utc = false) const;
String get_time_string_from_system(bool p_utc = false) const;
Dictionary get_time_zone_from_system() const;
double get_unix_time_from_system() const;
uint64_t get_ticks_msec() const;
uint64_t get_ticks_usec() const;
Time();
virtual ~Time();
};
#endif // TIME_H

View File

@ -65,6 +65,7 @@
#include "core/math/triangle_mesh.h"
#include "core/os/input.h"
#include "core/os/main_loop.h"
#include "core/os/time.h"
#include "core/packed_data_container.h"
#include "core/path_remap.h"
#include "core/project_settings.h"
@ -250,6 +251,7 @@ void register_core_singletons() {
ClassDB::register_class<InputMap>();
ClassDB::register_class<_JSON>();
ClassDB::register_class<Expression>();
ClassDB::register_class<Time>();
Engine::get_singleton()->add_singleton(Engine::Singleton("ProjectSettings", ProjectSettings::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("IP", IP::get_singleton()));
@ -264,6 +266,7 @@ void register_core_singletons() {
Engine::get_singleton()->add_singleton(Engine::Singleton("Input", Input::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("InputMap", InputMap::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("JSON", _JSON::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("Time", Time::get_singleton()));
}
void unregister_core_types() {

View File

@ -77,6 +77,9 @@
<member name="ResourceSaver" type="ResourceSaver" setter="" getter="">
The [ResourceSaver] singleton.
</member>
<member name="Time" type="Time" setter="" getter="">
The [Time] singleton.
</member>
<member name="TranslationServer" type="TranslationServer" setter="" getter="">
The [TranslationServer] singleton.
</member>

View File

@ -184,6 +184,7 @@
<return type="Dictionary" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Deprecated, use [method Time.get_date_dict_from_system] instead.
Returns current date as a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]weekday[/code], [code]dst[/code] (Daylight Savings Time).
</description>
</method>
@ -191,6 +192,7 @@
<return type="Dictionary" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Deprecated, use [method Time.get_datetime_dict_from_system] instead.
Returns current datetime as a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]weekday[/code], [code]dst[/code] (Daylight Savings Time), [code]hour[/code], [code]minute[/code], [code]second[/code].
</description>
</method>
@ -198,6 +200,7 @@
<return type="Dictionary" />
<argument index="0" name="unix_time_val" type="int" />
<description>
Deprecated, use [method Time.get_datetime_dict_from_unix_time] instead.
Gets a dictionary of time values corresponding to the given UNIX epoch time (in seconds).
The returned Dictionary's values will be the same as [method get_datetime], with the exception of Daylight Savings Time as it cannot be determined from the epoch.
</description>
@ -467,12 +470,14 @@
<method name="get_ticks_msec" qualifiers="const">
<return type="int" />
<description>
Deprecated, use [method Time.get_ticks_msec] instead.
Returns the amount of time passed in milliseconds since the engine started.
</description>
</method>
<method name="get_ticks_usec" qualifiers="const">
<return type="int" />
<description>
Deprecated, use [method Time.get_ticks_usec] instead.
Returns the amount of time passed in microseconds since the engine started.
</description>
</method>
@ -480,6 +485,7 @@
<return type="Dictionary" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Deprecated, use [method Time.get_time_dict_from_system] instead.
Returns current time as a dictionary of keys: hour, minute, second.
</description>
</method>

235
doc/classes/Time.xml Normal file
View File

@ -0,0 +1,235 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Time" inherits="Object" version="3.5">
<brief_description>
Time singleton for working with time.
</brief_description>
<description>
The Time singleton allows converting time between various formats and also getting time information from the system.
This class conforms with as many of the ISO 8601 standards as possible. All dates follow the Proleptic Gregorian calendar. As such, the day before [code]1582-10-15[/code] is [code]1582-10-14[/code], not [code]1582-10-04[/code]. The year before 1 AD (aka 1 BC) is number [code]0[/code], with the year before that (2 BC) being [code]-1[/code], etc.
Conversion methods assume "the same timezone", and do not handle timezone conversions or DST automatically. Leap seconds are also not handled, they must be done manually if desired. Suffixes such as "Z" are not handled, you need to strip them away manually.
When getting time information from the system, the time can either be in the local timezone or UTC depending on the [code]utc[/code] parameter. However, the [method get_unix_time_from_system] method always returns the time in UTC.
[b]Important:[/b] The [code]_from_system[/code] methods use the system clock that the user can manually set. [b]Never use[/b] this method for precise time calculation since its results are subject to automatic adjustments by the user or the operating system. [b]Always use[/b] [method get_ticks_usec] or [method get_ticks_msec] for precise time calculation instead, since they are guaranteed to be monotonic (i.e. never decrease).
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_date_dict_from_system" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Returns the current date as a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]weekday[/code], and [code]dst[/code] (Daylight Savings Time).
The returned values are in the system's local time when [code]utc[/code] is false, otherwise they are in UTC.
</description>
</method>
<method name="get_date_dict_from_unix_time" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="unix_time_val" type="int" />
<description>
Converts the given Unix timestamp to a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], and [code]weekday[/code].
</description>
</method>
<method name="get_date_string_from_system" qualifiers="const">
<return type="String" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Returns the current date as an ISO 8601 date string (YYYY-MM-DD).
The returned values are in the system's local time when [code]utc[/code] is false, otherwise they are in UTC.
</description>
</method>
<method name="get_date_string_from_unix_time" qualifiers="const">
<return type="String" />
<argument index="0" name="unix_time_val" type="int" />
<description>
Converts the given Unix timestamp to an ISO 8601 date string (YYYY-MM-DD).
</description>
</method>
<method name="get_datetime_dict_from_string" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="datetime" type="String" />
<argument index="1" name="weekday" type="bool" />
<description>
Converts the given ISO 8601 date and time string (YYYY-MM-DDTHH:MM:SS) to a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]weekday[/code], [code]hour[/code], [code]minute[/code], and [code]second[/code].
If [code]weekday[/code] is false, then the [code]weekday[/code] entry is excluded (the calculation is relatively expensive).
</description>
</method>
<method name="get_datetime_dict_from_system" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Returns the current date as a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]weekday[/code], [code]hour[/code], [code]minute[/code], and [code]second[/code].
</description>
</method>
<method name="get_datetime_dict_from_unix_time" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="unix_time_val" type="int" />
<description>
Converts the given Unix timestamp to a dictionary of keys: [code]year[/code], [code]month[/code], [code]day[/code], and [code]weekday[/code].
The returned Dictionary's values will be the same as the [method get_datetime_dict_from_system] if the Unix timestamp is the current time, with the exception of Daylight Savings Time as it cannot be determined from the epoch.
</description>
</method>
<method name="get_datetime_string_from_dict" qualifiers="const">
<return type="String" />
<argument index="0" name="datetime" type="Dictionary" />
<argument index="1" name="use_space" type="bool" />
<description>
Converts the given dictionary of keys to an ISO 8601 date and time string (YYYY-MM-DDTHH:MM:SS).
The given dictionary can be populated with the following keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]hour[/code], [code]minute[/code], and [code]second[/code]. Any other entries (including [code]dst[/code]) are ignored.
If the dictionary is empty, [code]0[/code] is returned. If some keys are omitted, they default to the equivalent values for the Unix epoch timestamp 0 (1970-01-01 at 00:00:00).
If [code]use_space[/code] is true, use a space instead of the letter T in the middle.
</description>
</method>
<method name="get_datetime_string_from_system" qualifiers="const">
<return type="String" />
<argument index="0" name="utc" type="bool" default="false" />
<argument index="1" name="use_space" type="bool" default="false" />
<description>
Returns the current date and time as an ISO 8601 date and time string (YYYY-MM-DDTHH:MM:SS).
The returned values are in the system's local time when [code]utc[/code] is false, otherwise they are in UTC.
If [code]use_space[/code] is true, use a space instead of the letter T in the middle.
</description>
</method>
<method name="get_datetime_string_from_unix_time" qualifiers="const">
<return type="String" />
<argument index="0" name="unix_time_val" type="int" />
<argument index="1" name="use_space" type="bool" default="false" />
<description>
Converts the given Unix timestamp to an ISO 8601 date and time string (YYYY-MM-DDTHH:MM:SS).
If [code]use_space[/code] is true, use a space instead of the letter T in the middle.
</description>
</method>
<method name="get_ticks_msec" qualifiers="const">
<return type="int" />
<description>
Returns the amount of time passed in milliseconds since the engine started.
Will always be positive or 0 and uses a 64-bit value (it will wrap after roughly 500 million years).
</description>
</method>
<method name="get_ticks_usec" qualifiers="const">
<return type="int" />
<description>
Returns the amount of time passed in microseconds since the engine started.
Will always be positive or 0 and uses a 64-bit value (it will wrap after roughly half a million years).
</description>
</method>
<method name="get_time_dict_from_system" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Returns the current time as a dictionary of keys: [code]hour[/code], [code]minute[/code], and [code]second[/code].
The returned values are in the system's local time when [code]utc[/code] is false, otherwise they are in UTC.
</description>
</method>
<method name="get_time_dict_from_unix_time" qualifiers="const">
<return type="Dictionary" />
<argument index="0" name="unix_time_val" type="int" />
<description>
Converts the given time to a dictionary of keys: [code]hour[/code], [code]minute[/code], and [code]second[/code].
</description>
</method>
<method name="get_time_string_from_system" qualifiers="const">
<return type="String" />
<argument index="0" name="utc" type="bool" default="false" />
<description>
Returns the current time as an ISO 8601 time string (HH:MM:SS).
The returned values are in the system's local time when [code]utc[/code] is false, otherwise they are in UTC.
</description>
</method>
<method name="get_time_string_from_unix_time" qualifiers="const">
<return type="String" />
<argument index="0" name="unix_time_val" type="int" />
<description>
Converts the given Unix timestamp to an ISO 8601 time string (HH:MM:SS).
</description>
</method>
<method name="get_time_zone_from_system" qualifiers="const">
<return type="Dictionary" />
<description>
Returns the current time zone as a dictionary of keys: [code]bias[/code] and [code]name[/code]. The [code]bias[/code] value is the offset from UTC in minutes, since not all time zones are multiples of an hour from UTC.
</description>
</method>
<method name="get_unix_time_from_datetime_dict" qualifiers="const">
<return type="int" />
<argument index="0" name="datetime" type="Dictionary" />
<description>
Converts a dictionary of time values to a Unix timestamp.
The given dictionary can be populated with the following keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]hour[/code], [code]minute[/code], and [code]second[/code]. Any other entries (including [code]dst[/code]) are ignored.
If the dictionary is empty, [code]0[/code] is returned. If some keys are omitted, they default to the equivalent values for the Unix epoch timestamp 0 (1970-01-01 at 00:00:00).
You can pass the output from [method get_datetime_dict_from_unix_time] directly into this function and get the same as what was put in.
[b]Note:[/b] Unix timestamps are often in UTC. This method does not do any timezone conversion, so the timestamp will be in the same timezone as the given datetime dictionary.
</description>
</method>
<method name="get_unix_time_from_datetime_string" qualifiers="const">
<return type="int" />
<argument index="0" name="datetime" type="String" />
<description>
Converts the given ISO 8601 date and/or time string to a Unix timestamp. The string can contain a date only, a time only, or both.
[b]Note:[/b] Unix timestamps are often in UTC. This method does not do any timezone conversion, so the timestamp will be in the same timezone as the given datetime string.
</description>
</method>
<method name="get_unix_time_from_system" qualifiers="const">
<return type="float" />
<description>
Returns the current Unix timestamp in seconds based on the system time in UTC. This method is implemented by the operating system and always returns the time in UTC.
</description>
</method>
</methods>
<constants>
<constant name="MONTH_JANUARY" value="1" enum="Month">
The month of January, represented numerically as [code]01[/code].
</constant>
<constant name="MONTH_FEBRUARY" value="2" enum="Month">
The month of February, represented numerically as [code]02[/code].
</constant>
<constant name="MONTH_MARCH" value="3" enum="Month">
The month of March, represented numerically as [code]03[/code].
</constant>
<constant name="MONTH_APRIL" value="4" enum="Month">
The month of April, represented numerically as [code]04[/code].
</constant>
<constant name="MONTH_MAY" value="5" enum="Month">
The month of May, represented numerically as [code]05[/code].
</constant>
<constant name="MONTH_JUNE" value="6" enum="Month">
The month of June, represented numerically as [code]06[/code].
</constant>
<constant name="MONTH_JULY" value="7" enum="Month">
The month of July, represented numerically as [code]07[/code].
</constant>
<constant name="MONTH_AUGUST" value="8" enum="Month">
The month of August, represented numerically as [code]08[/code].
</constant>
<constant name="MONTH_SEPTEMBER" value="9" enum="Month">
The month of September, represented numerically as [code]09[/code].
</constant>
<constant name="MONTH_OCTOBER" value="10" enum="Month">
The month of October, represented numerically as [code]10[/code].
</constant>
<constant name="MONTH_NOVEMBER" value="11" enum="Month">
The month of November, represented numerically as [code]11[/code].
</constant>
<constant name="MONTH_DECEMBER" value="12" enum="Month">
The month of December, represented numerically as [code]12[/code].
</constant>
<constant name="WEEKDAY_SUNDAY" value="0" enum="Weekday">
The day of the week Sunday, represented numerically as [code]0[/code].
</constant>
<constant name="WEEKDAY_MONDAY" value="1" enum="Weekday">
The day of the week Monday, represented numerically as [code]1[/code].
</constant>
<constant name="WEEKDAY_TUESDAY" value="2" enum="Weekday">
The day of the week Tuesday, represented numerically as [code]2[/code].
</constant>
<constant name="WEEKDAY_WEDNESDAY" value="3" enum="Weekday">
The day of the week Wednesday, represented numerically as [code]3[/code].
</constant>
<constant name="WEEKDAY_THURSDAY" value="4" enum="Weekday">
The day of the week Thursday, represented numerically as [code]4[/code].
</constant>
<constant name="WEEKDAY_FRIDAY" value="5" enum="Weekday">
The day of the week Friday, represented numerically as [code]5[/code].
</constant>
<constant name="WEEKDAY_SATURDAY" value="6" enum="Weekday">
The day of the week Saturday, represented numerically as [code]6[/code].
</constant>
</constants>
</class>

View File

@ -41,6 +41,7 @@
#include "core/message_queue.h"
#include "core/os/dir_access.h"
#include "core/os/os.h"
#include "core/os/time.h"
#include "core/project_settings.h"
#include "core/register_core_types.h"
#include "core/script_debugger_local.h"
@ -91,6 +92,7 @@ static InputMap *input_map = nullptr;
static TranslationServer *translation_server = nullptr;
static Performance *performance = nullptr;
static PackedData *packed_data = nullptr;
static Time *time_singleton = nullptr;
#ifdef MINIZIP_ENABLED
static ZipArchive *zip_packed_data = nullptr;
#endif
@ -378,6 +380,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
globals = memnew(ProjectSettings);
input_map = memnew(InputMap);
time_singleton = memnew(Time);
register_core_settings(); //here globals is present
@ -1260,6 +1263,9 @@ error:
if (input_map) {
memdelete(input_map);
}
if (time_singleton) {
memdelete(time_singleton);
}
if (translation_server) {
memdelete(translation_server);
}
@ -2406,6 +2412,9 @@ void Main::cleanup(bool p_force) {
if (input_map) {
memdelete(input_map);
}
if (time_singleton) {
memdelete(time_singleton);
}
if (translation_server) {
memdelete(translation_server);
}