有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类似于C mktime()的Java函数?

我正在将一些代码从C移植到Java。我在C中有一行:

time_t t0 = mktime(&EpochTime); 

其中,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()函数的设计目的


共 (1) 个答案

  1. # 1 楼答案

    使用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();