我正在将一些代码从C移植到Java中。我在 C 中有一行如下:
time_t t0 = mktime(&EpochTime);
其中纪元时间定义为:
struct tm EpochTime;
struct tm
定义为:
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
C 库函数time_t mktime(struct tm *timeptr)
根据本地时区将timeptr
指向的结构转换为time_t
值。
在我的 Java 代码中,我可以创建静态类变量以及 setter/getter 来表示结构数据。是否有一种库/技术可以实现mktime()
功能的设计目的?
使用 ZonedDateTime:
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime dateTime = ZonedDateTime.of(
year + 1900,
month + 1,
dayOfMonth,
hours,
minutes,
seconds,
0, // nanoseconds within second
zone);
long t = dateTime.toEpochSecond();
DayOfWeek wday = dateTime.getDayOfWeek();
int yday = dateTime.getDayOfYear();