如何获取 GMT 的 unixtimestamp

How to get the unixtimestamp for GMT

下面的函数给出了设备中当前时间的 unixtime

    public static long get_unix_time2(long seconds_since_midnight_gmt,
        int day_of_month) {
    long m_time = 0;
    Calendar cal = Calendar.getInstance();

    cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
    cal.set(Calendar.DAY_OF_MONTH, day_of_month); 
    m_time = cal.getTime().getTime();

    //Date current = Calendar.getInstance().getTime();
    //Date dateTime = new Date();
    //long diffInSeconds = (current.getTime() - dateTime.getTime()) / 1000;
    //long min = (diffInSeconds = (diffInSeconds / 60)) >= 60 ?   //diffInSeconds  % 60
        //  : diffInSeconds;

    // m_time = m_time - (min * -3600 * 1000);

    return m_time;
}

如何更改 unixtime,以便将来自设备的时间替换为作为参数收到的 "seconds_since_midnight_gmt" 值。

您可以设置 Calendar 对象的值。

cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, (int) seconds_since_midnight_gmt);

java.time

旧版日期时间 API(java.util 日期时间类型及其格式类型,SimpleDateFormat)已过时且容易出错。建议完全停止使用,改用java.timemodern date-time API*.

使用现代API的解决方案:

import java.time.Duration;
import java.time.YearMonth;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        //Test
        System.out.println(getUnixTime2(10000, 16));
    }

    public static long getUnixTime2(long secondsSinceMidnightGmt, int dayOfMonth) {
        return YearMonth.now()
                .atDay(dayOfMonth)
                .atStartOfDay(ZoneId.systemDefault())
                .plus(Duration.ofSeconds(secondsSinceMidnightGmt))
                .toInstant()
                .toEpochMilli();
    }
}

输出:

1621129600000

Trail: Date Time 中了解有关 modern date-time API* 的更多信息.


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and