Add Time singleton

This commit is contained in:
Aaron Franke 2021-05-24 07:54:05 -04:00
parent e82a1113ab
commit f64fea1b23
No known key found for this signature in database
GPG key ID: 40A1750B977E56BF
23 changed files with 1012 additions and 388 deletions

View file

@ -42,28 +42,6 @@
#include "core/os/keyboard.h"
#include "core/os/os.h"
/**
* Time constants borrowed from loc_time.h
*/
#define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */
#define SECS_DAY (24L * 60L * 60L)
#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
#define SECOND_KEY "second"
#define MINUTE_KEY "minute"
#define HOUR_KEY "hour"
#define DAY_KEY "day"
#define MONTH_KEY "month"
#define YEAR_KEY "year"
#define WEEKDAY_KEY "weekday"
#define DST_KEY "dst"
/// Table of number of days in each month (for regular year and leap year)
static const unsigned int 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 }
};
////// _ResourceLoader //////
_ResourceLoader *_ResourceLoader::singleton = nullptr;
@ -322,197 +300,6 @@ uint64_t _OS::get_static_memory_peak_usage() const {
return OS::get_singleton()->get_static_memory_peak_usage();
}
/**
* Get current datetime with consideration for utc and
* dst
*/
Dictionary _OS::get_datetime(bool utc) const {
Dictionary dated = get_date(utc);
Dictionary timed = get_time(utc);
List<Variant> keys;
timed.get_key_list(&keys);
for (int i = 0; i < keys.size(); i++) {
dated[keys[i]] = timed[keys[i]];
}
return dated;
}
Dictionary _OS::get_date(bool utc) const {
OS::Date date = OS::get_singleton()->get_date(utc);
Dictionary dated;
dated[YEAR_KEY] = date.year;
dated[MONTH_KEY] = date.month;
dated[DAY_KEY] = date.day;
dated[WEEKDAY_KEY] = date.weekday;
dated[DST_KEY] = date.dst;
return dated;
}
Dictionary _OS::get_time(bool utc) const {
OS::Time time = OS::get_singleton()->get_time(utc);
Dictionary timed;
timed[HOUR_KEY] = time.hour;
timed[MINUTE_KEY] = time.min;
timed[SECOND_KEY] = time.sec;
return timed;
}
/**
* Get an epoch time value from a dictionary of time values
* @p datetime must be populated with the following keys:
* day, hour, minute, month, second, year. (dst is ignored).
*
* You can pass the output from
* get_datetime_from_unix_time directly into this function
*
* @param datetime dictionary of date and time values to convert
*
* @return epoch calculated
*/
int64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
// if datetime is an empty Dictionary throws an error
ERR_FAIL_COND_V_MSG(datetime.is_empty(), 0, "Invalid datetime Dictionary: Dictionary is empty");
// Bunch of conversion constants
static const unsigned int SECONDS_PER_MINUTE = 60;
static const unsigned int MINUTES_PER_HOUR = 60;
static const unsigned int HOURS_PER_DAY = 24;
static const unsigned int SECONDS_PER_HOUR = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;
static const unsigned int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
// Get all time values from the dictionary, set to zero if it doesn't exist.
// Risk incorrect calculation over throwing errors
unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast<unsigned int>(datetime[SECOND_KEY]) : 0);
unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]) : 0);
unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]) : 0);
unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]) : 1);
unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) : 1);
unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(datetime[YEAR_KEY]) : 1970);
/// How many days come before each month (0-12)
static const unsigned short int DAYS_PAST_THIS_YEAR_TABLE[2][13] = {
/* Normal years. */
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
/* Leap years. */
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
};
ERR_FAIL_COND_V_MSG(second > 59, 0, "Invalid second value of: " + itos(second) + ".");
ERR_FAIL_COND_V_MSG(minute > 59, 0, "Invalid minute value of: " + itos(minute) + ".");
ERR_FAIL_COND_V_MSG(hour > 23, 0, "Invalid hour value of: " + itos(hour) + ".");
ERR_FAIL_COND_V_MSG(year == 0, 0, "Years before 1 AD are not supported. Value passed: " + itos(year) + ".");
ERR_FAIL_COND_V_MSG(month > 12 || month == 0, 0, "Invalid month value of: " + itos(month) + ".");
// Do this check after month is tested as valid
unsigned int days_in_month = MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1];
ERR_FAIL_COND_V_MSG(day == 0 || day > days_in_month, 0, "Invalid day value of: " + itos(day) + ". It should be comprised between 1 and " + itos(days_in_month) + " for month " + itos(month) + ".");
// Calculate all the seconds from months past in this year
uint64_t SECONDS_FROM_MONTHS_PAST_THIS_YEAR = DAYS_PAST_THIS_YEAR_TABLE[LEAPYEAR(year)][month - 1] * SECONDS_PER_DAY;
int64_t SECONDS_FROM_YEARS_PAST = 0;
if (year >= EPOCH_YR) {
for (unsigned int iyear = EPOCH_YR; iyear < year; iyear++) {
SECONDS_FROM_YEARS_PAST += YEARSIZE(iyear) * SECONDS_PER_DAY;
}
} else {
for (unsigned int iyear = EPOCH_YR - 1; iyear >= year; iyear--) {
SECONDS_FROM_YEARS_PAST -= YEARSIZE(iyear) * SECONDS_PER_DAY;
}
}
int64_t epoch =
second +
minute * SECONDS_PER_MINUTE +
hour * SECONDS_PER_HOUR +
// Subtract 1 from day, since the current day isn't over yet
// and we cannot count all 24 hours.
(day - 1) * SECONDS_PER_DAY +
SECONDS_FROM_MONTHS_PAST_THIS_YEAR +
SECONDS_FROM_YEARS_PAST;
return epoch;
}
/**
* Get a dictionary of time values when given epoch time
*
* Dictionary Time values will be a union if values from #get_time
* and #get_date dictionaries (with the exception of dst =
* day light standard time, as it cannot be determined from epoch)
*
* @param unix_time_val epoch time to convert
*
* @return dictionary of date and time values
*/
Dictionary _OS::get_datetime_from_unix_time(int64_t unix_time_val) const {
OS::Date date;
OS::Time time;
long dayclock, dayno;
int year = EPOCH_YR;
if (unix_time_val >= 0) {
dayno = unix_time_val / SECS_DAY;
dayclock = unix_time_val % SECS_DAY;
/* day 0 was a thursday */
date.weekday = static_cast<OS::Weekday>((dayno + 4) % 7);
while (dayno >= YEARSIZE(year)) {
dayno -= YEARSIZE(year);
year++;
}
} else {
dayno = (unix_time_val - SECS_DAY + 1) / SECS_DAY;
dayclock = unix_time_val - dayno * SECS_DAY;
date.weekday = static_cast<OS::Weekday>(((dayno % 7) + 11) % 7);
do {
year--;
dayno += YEARSIZE(year);
} while (dayno < 0);
}
time.sec = dayclock % 60;
time.min = (dayclock % 3600) / 60;
time.hour = dayclock / 3600;
date.year = year;
size_t imonth = 0;
while ((unsigned long)dayno >= MONTH_DAYS_TABLE[LEAPYEAR(year)][imonth]) {
dayno -= MONTH_DAYS_TABLE[LEAPYEAR(year)][imonth];
imonth++;
}
/// Add 1 to month to make sure months are indexed starting at 1
date.month = static_cast<OS::Month>(imonth + 1);
date.day = dayno + 1;
Dictionary timed;
timed[HOUR_KEY] = time.hour;
timed[MINUTE_KEY] = time.min;
timed[SECOND_KEY] = time.sec;
timed[YEAR_KEY] = date.year;
timed[MONTH_KEY] = date.month;
timed[DAY_KEY] = date.day;
timed[WEEKDAY_KEY] = date.weekday;
return timed;
}
Dictionary _OS::get_time_zone_info() const {
OS::TimeZoneInfo info = OS::get_singleton()->get_time_zone_info();
Dictionary infod;
infod["bias"] = info.bias;
infod["name"] = info.name;
return infod;
}
double _OS::get_unix_time() const {
return OS::get_singleton()->get_unix_time();
}
/** This method uses a signed argument for better error reporting as it's used from the scripting API. */
void _OS::delay_usec(int p_usec) const {
ERR_FAIL_COND_MSG(
@ -529,14 +316,6 @@ void _OS::delay_msec(int p_msec) const {
OS::get_singleton()->delay_usec(int64_t(p_msec) * 1000);
}
uint32_t _OS::get_ticks_msec() const {
return OS::get_singleton()->get_ticks_msec();
}
uint64_t _OS::get_ticks_usec() const {
return OS::get_singleton()->get_ticks_usec();
}
bool _OS::can_use_threads() const {
return OS::get_singleton()->can_use_threads();
}
@ -716,18 +495,8 @@ void _OS::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_name"), &_OS::get_name);
ClassDB::bind_method(D_METHOD("get_cmdline_args"), &_OS::get_cmdline_args);
ClassDB::bind_method(D_METHOD("get_datetime", "utc"), &_OS::get_datetime, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_date", "utc"), &_OS::get_date, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_time", "utc"), &_OS::get_time, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_time_zone_info"), &_OS::get_time_zone_info);
ClassDB::bind_method(D_METHOD("get_unix_time"), &_OS::get_unix_time);
ClassDB::bind_method(D_METHOD("get_datetime_from_unix_time", "unix_time_val"), &_OS::get_datetime_from_unix_time);
ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime", "datetime"), &_OS::get_unix_time_from_datetime);
ClassDB::bind_method(D_METHOD("delay_usec", "usec"), &_OS::delay_usec);
ClassDB::bind_method(D_METHOD("delay_msec", "msec"), &_OS::delay_msec);
ClassDB::bind_method(D_METHOD("get_ticks_msec"), &_OS::get_ticks_msec);
ClassDB::bind_method(D_METHOD("get_ticks_usec"), &_OS::get_ticks_usec);
ClassDB::bind_method(D_METHOD("get_locale"), &_OS::get_locale);
ClassDB::bind_method(D_METHOD("get_model_name"), &_OS::get_model_name);

View file

@ -199,14 +199,6 @@ public:
void set_use_file_access_save_and_swap(bool p_enable);
Dictionary get_date(bool utc) const;
Dictionary get_time(bool utc) const;
Dictionary get_datetime(bool utc) const;
Dictionary get_datetime_from_unix_time(int64_t unix_time_val) const;
int64_t get_unix_time_from_datetime(Dictionary datetime) const;
Dictionary get_time_zone_info() const;
double get_unix_time() const;
uint64_t get_static_memory_usage() const;
uint64_t get_static_memory_peak_usage() const;

View file

@ -33,6 +33,7 @@
#include "core/config/project_settings.h"
#include "core/os/dir_access.h"
#include "core/os/os.h"
#include "core/os/time.h"
#include "core/string/print_string.h"
#if defined(MINGW_ENABLED) || defined(_MSC_VER)
@ -156,11 +157,7 @@ void RotatedFileLogger::rotate_file() {
if (FileAccess::exists(base_path)) {
if (max_files > 1) {
char timestamp[21];
OS::Date date = OS::get_singleton()->get_date();
OS::Time time = OS::get_singleton()->get_time();
sprintf(timestamp, "_%04d-%02d-%02d_%02d.%02d.%02d", date.year, date.month, date.day, time.hour, time.min, time.sec);
String timestamp = Time::get_singleton()->get_datetime_string_from_system().replace(":", ".");
String backup_name = base_path.get_basename() + timestamp;
if (base_path.get_extension() != String()) {
backup_name += "." + base_path.get_extension();

View file

@ -47,37 +47,8 @@ OS *OS::get_singleton() {
return singleton;
}
uint32_t OS::get_ticks_msec() const {
return get_ticks_usec() / 1000;
}
String OS::get_iso_date_time(bool local) const {
OS::Date date = get_date(local);
OS::Time time = get_time(local);
String timezone;
if (!local) {
TimeZoneInfo zone = get_time_zone_info();
if (zone.bias >= 0) {
timezone = "+";
}
timezone = timezone + itos(zone.bias / 60).pad_zeros(2) + itos(zone.bias % 60).pad_zeros(2);
} else {
timezone = "Z";
}
return itos(date.year).pad_zeros(2) +
"-" +
itos(date.month).pad_zeros(2) +
"-" +
itos(date.day).pad_zeros(2) +
"T" +
itos(time.hour).pad_zeros(2) +
":" +
itos(time.min).pad_zeros(2) +
":" +
itos(time.sec).pad_zeros(2) +
timezone;
uint64_t OS::get_ticks_msec() const {
return get_ticks_usec() / 1000ULL;
}
double OS::get_unix_time() const {

View file

@ -158,17 +158,17 @@ public:
virtual void yield();
enum Weekday {
DAY_SUNDAY,
DAY_MONDAY,
DAY_TUESDAY,
DAY_WEDNESDAY,
DAY_THURSDAY,
DAY_FRIDAY,
DAY_SATURDAY
enum Weekday : uint8_t {
WEEKDAY_SUNDAY,
WEEKDAY_MONDAY,
WEEKDAY_TUESDAY,
WEEKDAY_WEDNESDAY,
WEEKDAY_THURSDAY,
WEEKDAY_FRIDAY,
WEEKDAY_SATURDAY,
};
enum Month {
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,
@ -182,21 +182,21 @@ public:
MONTH_SEPTEMBER,
MONTH_OCTOBER,
MONTH_NOVEMBER,
MONTH_DECEMBER
MONTH_DECEMBER,
};
struct Date {
int year;
int64_t year;
Month month;
int day;
uint8_t day;
Weekday weekday;
bool dst;
};
struct Time {
int hour;
int min;
int sec;
uint8_t hour;
uint8_t minute;
uint8_t second;
};
struct TimeZoneInfo {
@ -207,14 +207,13 @@ public:
virtual Date get_date(bool local = false) const = 0;
virtual Time get_time(bool local = false) const = 0;
virtual TimeZoneInfo get_time_zone_info() const = 0;
virtual String get_iso_date_time(bool local = false) const;
virtual double get_unix_time() const;
virtual void delay_usec(uint32_t p_usec) const = 0;
virtual void add_frame_delay(bool p_can_draw);
virtual uint64_t get_ticks_usec() const = 0;
uint32_t get_ticks_msec() const;
uint64_t get_ticks_msec() const;
virtual bool is_userfs_persistent() const { return true; }

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; \
PackedStringArray array = p_datetime.split("T"); \
date = array[0]; \
time = array[1]; \
} else if (p_datetime.find_char(' ') > 0) { \
has_date = has_time = true; \
PackedStringArray 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) { \
PackedInt32Array 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) { \
PackedInt32Array 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.is_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.is_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.minute;
datetime[SECOND_KEY] = time.second;
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.minute;
time_dictionary[SECOND_KEY] = time.second;
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.minute, time.second);
} else {
timestamp = vformat("%sT%02d:%02d:%02d", timestamp, time.hour, time.minute, time.second);
}
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.minute, time.second);
}
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/object/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

@ -68,6 +68,7 @@
#include "core/object/class_db.h"
#include "core/object/undo_redo.h"
#include "core/os/main_loop.h"
#include "core/os/time.h"
#include "core/string/optimized_translation.h"
#include "core/string/translation.h"
@ -258,6 +259,7 @@ void register_core_singletons() {
ClassDB::register_class<_JSON>();
ClassDB::register_class<Expression>();
ClassDB::register_class<_EngineDebugger>();
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()));
@ -274,6 +276,7 @@ void register_core_singletons() {
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("EngineDebugger", _EngineDebugger::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("Time", Time::get_singleton()));
}
void unregister_core_types() {

View file

@ -1261,6 +1261,9 @@
<member name="TextServerManager" type="TextServerManager" setter="" getter="">
The [TextServerManager] 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

@ -188,7 +188,7 @@
<argument index="0" name="file" type="String">
</argument>
<description>
Returns the last time the [code]file[/code] was modified in unix timestamp format or returns a [String] "ERROR IN [code]file[/code]". This unix timestamp can be converted to datetime by using [method OS.get_datetime_from_unix_time].
Returns the last time the [code]file[/code] was modified in Unix timestamp format or returns a [String] "ERROR IN [code]file[/code]". This Unix timestamp can be converted to another format using the [Time] singleton.
</description>
</method>
<method name="get_pascal_string">

View file

@ -176,34 +176,6 @@
[b]Note:[/b] This method is implemented on Linux, macOS and Windows.
</description>
</method>
<method name="get_date" qualifiers="const">
<return type="Dictionary">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<description>
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>
<method name="get_datetime" qualifiers="const">
<return type="Dictionary">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<description>
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>
<method name="get_datetime_from_unix_time" qualifiers="const">
<return type="Dictionary">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<description>
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>
</method>
<method name="get_environment" qualifiers="const">
<return type="String">
</return>
@ -320,36 +292,6 @@
[b]Note:[/b] Thread IDs are not deterministic and may be reused across application restarts.
</description>
</method>
<method name="get_ticks_msec" qualifiers="const">
<return type="int">
</return>
<description>
Returns the amount of time passed in milliseconds since the engine started.
</description>
</method>
<method name="get_ticks_usec" qualifiers="const">
<return type="int">
</return>
<description>
Returns the amount of time passed in microseconds since the engine started.
</description>
</method>
<method name="get_time" qualifiers="const">
<return type="Dictionary">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<description>
Returns current time as a dictionary of keys: hour, minute, second.
</description>
</method>
<method name="get_time_zone_info" qualifiers="const">
<return type="Dictionary">
</return>
<description>
Returns the current time zone as a dictionary with the keys: bias and name.
</description>
</method>
<method name="get_unique_id" qualifiers="const">
<return type="String">
</return>
@ -359,26 +301,6 @@
[b]Note:[/b] Returns an empty string on HTML5 and UWP, as this method isn't implemented on those platforms yet.
</description>
</method>
<method name="get_unix_time" qualifiers="const">
<return type="float">
</return>
<description>
Returns the current UNIX epoch timestamp in seconds.
[b]Important:[/b] This is the system clock that the user can manually set. [b]Never use[/b] this method for precise time calculation since its results are also subject to automatic adjustments by 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>
</method>
<method name="get_unix_time_from_datetime" qualifiers="const">
<return type="int">
</return>
<argument index="0" name="datetime" type="Dictionary">
</argument>
<description>
Gets an epoch time value from a dictionary of time values.
[code]datetime[/code] must be populated with the following keys: [code]year[/code], [code]month[/code], [code]day[/code], [code]hour[/code], [code]minute[/code], [code]second[/code].
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 UTC).
You can pass the output from [method get_datetime_from_unix_time] directly into this function. Daylight Savings Time ([code]dst[/code]), if present, is ignored.
</description>
</method>
<method name="get_user_data_dir" qualifiers="const">
<return type="String">
</return>

270
doc/classes/Time.xml Normal file
View file

@ -0,0 +1,270 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Time" inherits="Object" version="4.0">
<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.
[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">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<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">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<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">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<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">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<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">
</return>
<argument index="0" name="datetime" type="String">
</argument>
<argument index="1" name="weekday" type="bool">
</argument>
<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">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<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">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<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">
</return>
<argument index="0" name="datetime" type="Dictionary">
</argument>
<argument index="1" name="use_space" type="bool">
</argument>
<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">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<argument index="1" name="use_space" type="bool" default="false">
</argument>
<description>
Returns the current date and time 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], 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.
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">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<argument index="1" name="use_space" type="bool" default="false">
</argument>
<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">
</return>
<description>
Returns the amount of time passed in milliseconds since the engine started.
</description>
</method>
<method name="get_ticks_usec" qualifiers="const">
<return type="int">
</return>
<description>
Returns the amount of time passed in microseconds since the engine started.
</description>
</method>
<method name="get_time_dict_from_system" qualifiers="const">
<return type="Dictionary">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<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">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<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">
</return>
<argument index="0" name="utc" type="bool" default="false">
</argument>
<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">
</return>
<argument index="0" name="unix_time_val" type="int">
</argument>
<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">
</return>
<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">
</return>
<argument index="0" name="datetime" type="Dictionary">
</argument>
<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.
</description>
</method>
<method name="get_unix_time_from_datetime_string" qualifiers="const">
<return type="int">
</return>
<argument index="0" name="datetime" type="String">
</argument>
<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.
</description>
</method>
<method name="get_unix_time_from_system" qualifiers="const">
<return type="float">
</return>
<description>
Returns the current Unix timestamp in seconds based on the system time.
</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

@ -96,7 +96,7 @@
<return type="int">
</return>
<description>
Returns the absolute timestamp (in μs) of the last [XRServer] commit of the AR/VR eyes to [RenderingServer]. The value comes from an internal call to [method OS.get_ticks_usec].
Returns the absolute timestamp (in μs) of the last [XRServer] commit of the AR/VR eyes to [RenderingServer]. The value comes from an internal call to [method Time.get_ticks_usec].
</description>
</method>
<method name="get_last_frame_usec">
@ -110,7 +110,7 @@
<return type="int">
</return>
<description>
Returns the absolute timestamp (in μs) of the last [XRServer] process callback. The value comes from an internal call to [method OS.get_ticks_usec].
Returns the absolute timestamp (in μs) of the last [XRServer] process callback. The value comes from an internal call to [method Time.get_ticks_usec].
</description>
</method>
<method name="get_reference_frame" qualifiers="const">

View file

@ -195,8 +195,8 @@ OS::Time OS_Unix::get_time(bool utc) const {
}
Time ret;
ret.hour = lt.tm_hour;
ret.min = lt.tm_min;
ret.sec = lt.tm_sec;
ret.minute = lt.tm_min;
ret.second = lt.tm_sec;
get_time_zone_info();
return ret;
}

View file

@ -43,6 +43,7 @@
#include "core/os/file_access.h"
#include "core/os/keyboard.h"
#include "core/os/os.h"
#include "core/os/time.h"
#include "core/string/print_string.h"
#include "core/string/translation.h"
#include "core/version.h"
@ -2823,7 +2824,7 @@ void EditorNode::_request_screenshot() {
}
void EditorNode::_screenshot(bool p_use_utc) {
String name = "editor_screenshot_" + OS::get_singleton()->get_iso_date_time(p_use_utc).replace(":", "") + ".png";
String name = "editor_screenshot_" + Time::get_singleton()->get_datetime_string_from_system(p_use_utc).replace(":", "") + ".png";
NodePath path = String("user://") + name;
_save_screenshot(path);
if (EditorSettings::get_singleton()->get("interface/editor/automatically_open_screenshots")) {

View file

@ -45,6 +45,7 @@
#include "core/object/message_queue.h"
#include "core/os/dir_access.h"
#include "core/os/os.h"
#include "core/os/time.h"
#include "core/register_core_types.h"
#include "core/string/translation.h"
#include "core/version.h"
@ -101,6 +102,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
@ -532,6 +534,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
MAIN_PRINT("Main: Initialize Globals");
input_map = memnew(InputMap);
time_singleton = memnew(Time);
globals = memnew(ProjectSettings);
register_core_settings(); //here globals are present
@ -1402,6 +1405,9 @@ error:
if (input_map) {
memdelete(input_map);
}
if (time_singleton) {
memdelete(time_singleton);
}
if (translation_server) {
memdelete(translation_server);
}
@ -2667,6 +2673,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);
}

View file

@ -161,8 +161,8 @@ void GDMonoLog::initialize() {
OS::Time time_now = OS::get_singleton()->get_time();
String log_file_name = str_format("%04d-%02d-%02d_%02d.%02d.%02d",
date_now.year, date_now.month, date_now.day,
time_now.hour, time_now.min, time_now.sec);
(int)date_now.year, (int)date_now.month, (int)date_now.day,
(int)time_now.hour, (int)time_now.minute, (int)time_now.second);
log_file_name += str_format("_%d", OS::get_singleton()->get_process_id());

View file

@ -609,9 +609,9 @@ class EditorExportPlatformAndroid : public EditorExportPlatform {
zip_fileinfo zipfi;
zipfi.tmz_date.tm_hour = time.hour;
zipfi.tmz_date.tm_mday = date.day;
zipfi.tmz_date.tm_min = time.min;
zipfi.tmz_date.tm_min = time.minute;
zipfi.tmz_date.tm_mon = date.month - 1; // tm_mon is zero indexed
zipfi.tmz_date.tm_sec = time.sec;
zipfi.tmz_date.tm_sec = time.second;
zipfi.tmz_date.tm_year = date.year;
zipfi.dosDate = 0;
zipfi.external_fa = 0;

View file

@ -425,8 +425,8 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) {
// Generates the .trashinfo file
OS::Date date = OS::get_singleton()->get_date(false);
OS::Time time = OS::get_singleton()->get_time(false);
String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, date.month, date.day, time.hour, time.min);
timestamp = vformat("%s%02d", timestamp, time.sec); // vformat only supports up to 6 arguments.
String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, date.month, date.day, time.hour, time.minute);
timestamp = vformat("%s%02d", timestamp, time.second); // vformat only supports up to 6 arguments.
String trash_info = "[Trash Info]\nPath=" + p_path.uri_encode() + "\nDeletionDate=" + timestamp + "\n";
{
Error err;

View file

@ -1000,9 +1000,9 @@ void EditorExportPlatformOSX::_zip_folder_recursive(zipFile &p_zip, const String
zip_fileinfo zipfi;
zipfi.tmz_date.tm_hour = time.hour;
zipfi.tmz_date.tm_mday = date.day;
zipfi.tmz_date.tm_min = time.min;
zipfi.tmz_date.tm_min = time.minute;
zipfi.tmz_date.tm_mon = date.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, http://www.cplusplus.com/reference/ctime/tm/
zipfi.tmz_date.tm_sec = time.sec;
zipfi.tmz_date.tm_sec = time.second;
zipfi.tmz_date.tm_year = date.year;
zipfi.dosDate = 0;
// 0120000: symbolic link type
@ -1045,9 +1045,9 @@ void EditorExportPlatformOSX::_zip_folder_recursive(zipFile &p_zip, const String
zip_fileinfo zipfi;
zipfi.tmz_date.tm_hour = time.hour;
zipfi.tmz_date.tm_mday = date.day;
zipfi.tmz_date.tm_min = time.min;
zipfi.tmz_date.tm_min = time.minute;
zipfi.tmz_date.tm_mon = date.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, http://www.cplusplus.com/reference/ctime/tm/
zipfi.tmz_date.tm_sec = time.sec;
zipfi.tmz_date.tm_sec = time.second;
zipfi.tmz_date.tm_year = date.year;
zipfi.dosDate = 0;
// 0100000: regular file type

View file

@ -315,8 +315,8 @@ OS::Time OS_Windows::get_time(bool utc) const {
Time time;
time.hour = systemtime.wHour;
time.min = systemtime.wMinute;
time.sec = systemtime.wSecond;
time.minute = systemtime.wMinute;
time.second = systemtime.wSecond;
return time;
}

View file

@ -74,6 +74,7 @@
#include "test_shader_lang.h"
#include "test_string.h"
#include "test_text_server.h"
#include "test_time.h"
#include "test_translation.h"
#include "test_validate_testing.h"
#include "test_variant.h"

145
tests/test_time.h Normal file
View file

@ -0,0 +1,145 @@
/*************************************************************************/
/* test_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 TEST_TIME_H
#define TEST_TIME_H
#include "core/os/time.h"
#include "thirdparty/doctest/doctest.h"
#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"
namespace TestTime {
TEST_CASE("[Time] Unix time conversion to/from datetime string") {
const Time *time = Time::get_singleton();
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1970-01-01T00:00:00") == 0, "Time get_unix_time_from_datetime_string: The timestamp for Unix epoch is zero.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1970-01-01 00:00:00") == 0, "Time get_unix_time_from_datetime_string: The timestamp for Unix epoch with space is zero.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1970-01-01") == 0, "Time get_unix_time_from_datetime_string: The timestamp for Unix epoch without time is zero.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("00:00:00") == 0, "Time get_unix_time_from_datetime_string: The timestamp for zero time without date is zero.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1969-12-31T23:59:59") == -1, "Time get_unix_time_from_datetime_string: The timestamp for just before Unix epoch is negative one.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1234-05-06T07:08:09") == -23215049511, "Time get_unix_time_from_datetime_string: The timestamp for an arbitrary datetime is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1234-05-06 07:08:09") == -23215049511, "Time get_unix_time_from_datetime_string: The timestamp for an arbitrary datetime with space is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1234-05-06") == -23215075200, "Time get_unix_time_from_datetime_string: The timestamp for an arbitrary date without time is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("07:08:09") == 25689, "Time get_unix_time_from_datetime_string: The timestamp for an arbitrary time without date is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("2014-02-09T22:10:30") == 1391983830, "Time get_unix_time_from_datetime_string: The timestamp for GODOT IS OPEN SOURCE is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("2014-02-09 22:10:30") == 1391983830, "Time get_unix_time_from_datetime_string: The timestamp for GODOT IS OPEN SOURCE with space is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("2014-02-09") == 1391904000, "Time get_unix_time_from_datetime_string: The date for GODOT IS OPEN SOURCE without time is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("22:10:30") == 79830, "Time get_unix_time_from_datetime_string: The time for GODOT IS OPEN SOURCE without date is as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("-1000000000-01-01T00:00:00") == -31557014167219200, "Time get_unix_time_from_datetime_string: In the year negative a billion, Japan might not have been here.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string("1000000-01-01T00:00:00") == 31494784780800, "Time get_unix_time_from_datetime_string: The timestamp for the year a million is as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(0) == "1970-01-01T00:00:00", "Time get_datetime_string_from_unix_time: The timestamp string for Unix epoch is zero.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(0, true) == "1970-01-01 00:00:00", "Time get_datetime_string_from_unix_time: The timestamp string for Unix epoch with space is zero.");
CHECK_MESSAGE(time->get_date_string_from_unix_time(0) == "1970-01-01", "Time get_date_string_from_unix_time: The date string for zero is Unix epoch date.");
CHECK_MESSAGE(time->get_time_string_from_unix_time(0) == "00:00:00", "Time get_time_string_from_unix_time: The date for zero zero is Unix epoch date.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(-1) == "1969-12-31T23:59:59", "Time get_time_string_from_unix_time: The timestamp string for just before Unix epoch is as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(-23215049511) == "1234-05-06T07:08:09", "Time get_datetime_string_from_unix_time: The timestamp for an arbitrary datetime is as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(-23215049511, true) == "1234-05-06 07:08:09", "Time get_datetime_string_from_unix_time: The timestamp for an arbitrary datetime with space is as expected.");
CHECK_MESSAGE(time->get_date_string_from_unix_time(-23215075200) == "1234-05-06", "Time get_date_string_from_unix_time: The timestamp for an arbitrary date without time is as expected.");
CHECK_MESSAGE(time->get_time_string_from_unix_time(25689) == "07:08:09", "Time get_time_string_from_unix_time: The timestamp for an arbitrary time without date is as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(1391983830) == "2014-02-09T22:10:30", "Time get_datetime_string_from_unix_time: The timestamp for GODOT IS OPEN SOURCE is as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(1391983830, true) == "2014-02-09 22:10:30", "Time get_datetime_string_from_unix_time: The timestamp for GODOT IS OPEN SOURCE with space is as expected.");
CHECK_MESSAGE(time->get_date_string_from_unix_time(1391904000) == "2014-02-09", "Time get_date_string_from_unix_time: The date for GODOT IS OPEN SOURCE without time is as expected.");
CHECK_MESSAGE(time->get_time_string_from_unix_time(79830) == "22:10:30", "Time get_time_string_from_unix_time: The time for GODOT IS OPEN SOURCE without date is as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_unix_time(31494784780800) == "1000000-01-01T00:00:00", "Time get_datetime_string_from_unix_time: The timestamp for the year a million is as expected.");
}
TEST_CASE("[Time] Datetime dictionary conversion methods") {
const Time *time = Time::get_singleton();
Dictionary datetime;
datetime[YEAR_KEY] = 2014;
datetime[MONTH_KEY] = 2;
datetime[DAY_KEY] = 9;
datetime[WEEKDAY_KEY] = Time::Weekday::WEEKDAY_SUNDAY;
datetime[HOUR_KEY] = 22;
datetime[MINUTE_KEY] = 10;
datetime[SECOND_KEY] = 30;
Dictionary date_only;
date_only[YEAR_KEY] = 2014;
date_only[MONTH_KEY] = 2;
date_only[DAY_KEY] = 9;
date_only[WEEKDAY_KEY] = Time::Weekday::WEEKDAY_SUNDAY;
Dictionary time_only;
time_only[HOUR_KEY] = 22;
time_only[MINUTE_KEY] = 10;
time_only[SECOND_KEY] = 30;
CHECK_MESSAGE(time->get_unix_time_from_datetime_dict(datetime) == 1391983830, "Time get_unix_time_from_datetime_dict: The datetime dictionary for GODOT IS OPEN SOURCE is converted to a timestamp as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_dict(date_only) == 1391904000, "Time get_unix_time_from_datetime_dict: The date dictionary for GODOT IS OPEN SOURCE is converted to a timestamp as expected.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_dict(time_only) == 79830, "Time get_unix_time_from_datetime_dict: The time dictionary for GODOT IS OPEN SOURCE is converted to a timestamp as expected.");
CHECK_MESSAGE(time->get_datetime_dict_from_unix_time(1391983830).hash() == datetime.hash(), "Time get_datetime_dict_from_unix_time: The datetime timestamp for GODOT IS OPEN SOURCE is converted to a dictionary as expected.");
CHECK_MESSAGE(time->get_date_dict_from_unix_time(1391904000).hash() == date_only.hash(), "Time get_date_dict_from_unix_time: The date timestamp for GODOT IS OPEN SOURCE is converted to a dictionary as expected.");
CHECK_MESSAGE(time->get_time_dict_from_unix_time(79830).hash() == time_only.hash(), "Time get_time_dict_from_unix_time: The time timestamp for GODOT IS OPEN SOURCE is converted to a dictionary as expected.");
CHECK_MESSAGE((Time::Weekday)(int)time->get_datetime_dict_from_unix_time(0)[WEEKDAY_KEY] == Time::Weekday::WEEKDAY_THURSDAY, "Time get_datetime_dict_from_unix_time: The weekday for the Unix epoch is a Thursday as expected.");
CHECK_MESSAGE((Time::Weekday)(int)time->get_datetime_dict_from_unix_time(1391983830)[WEEKDAY_KEY] == Time::Weekday::WEEKDAY_SUNDAY, "Time get_datetime_dict_from_unix_time: The weekday for GODOT IS OPEN SOURCE is a Sunday as expected.");
CHECK_MESSAGE(time->get_datetime_dict_from_string("2014-02-09T22:10:30").hash() == datetime.hash(), "Time get_datetime_dict_from_string: The dictionary from string for GODOT IS OPEN SOURCE works as expected.");
CHECK_MESSAGE(!time->get_datetime_dict_from_string("2014-02-09T22:10:30", false).has(WEEKDAY_KEY), "Time get_datetime_dict_from_string: The dictionary from string for GODOT IS OPEN SOURCE without weekday doesn't contain the weekday key as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_dict(datetime) == "2014-02-09T22:10:30", "Time get_datetime_string_from_dict: The string from dictionary for GODOT IS OPEN SOURCE works as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_dict(time->get_datetime_dict_from_string("2014-02-09T22:10:30")) == "2014-02-09T22:10:30", "Time get_datetime_string_from_dict: The round-trip string to dict to string GODOT IS OPEN SOURCE works as expected.");
CHECK_MESSAGE(time->get_datetime_string_from_dict(time->get_datetime_dict_from_string("2014-02-09 22:10:30"), true) == "2014-02-09 22:10:30", "Time get_datetime_string_from_dict: The round-trip string to dict to string GODOT IS OPEN SOURCE with spaces works as expected.");
}
TEST_CASE("[Time] System time methods") {
const Time *time = Time::get_singleton();
const uint64_t ticks_msec = time->get_ticks_msec();
const uint64_t ticks_usec = time->get_ticks_usec();
CHECK_MESSAGE(time->get_unix_time_from_system() > 1000000000, "Time get_unix_time_from_system: The timestamp from system time doesn't fail and is very positive.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_dict(time->get_datetime_dict_from_system()) > 1000000000, "Time get_datetime_string_from_system: The timestamp from system time doesn't fail and is very positive.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_dict(time->get_date_dict_from_system()) > 1000000000, "Time get_datetime_string_from_system: The date from system time doesn't fail and is very positive.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_dict(time->get_time_dict_from_system()) < 86400, "Time get_datetime_string_from_system: The time from system time doesn't fail and is within the acceptable range.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string(time->get_datetime_string_from_system()) > 1000000000, "Time get_datetime_string_from_system: The timestamp from system time doesn't fail and is very positive.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string(time->get_date_string_from_system()) > 1000000000, "Time get_datetime_string_from_system: The date from system time doesn't fail and is very positive.");
CHECK_MESSAGE(time->get_unix_time_from_datetime_string(time->get_time_string_from_system()) < 86400, "Time get_datetime_string_from_system: The time from system time doesn't fail and is within the acceptable range.");
CHECK_MESSAGE(time->get_ticks_msec() >= ticks_msec, "Time get_ticks_msec: The value has not decreased.");
CHECK_MESSAGE(time->get_ticks_usec() > ticks_usec, "Time get_ticks_usec: The value has increased.");
}
} // namespace TestTime
#endif // TEST_TIME_H