30 分钟前获取 Android Unix Epoch?

Get Android Unix Epoch 30 Minutes Before Now?

我知道您可以使用以下代码在 android 应用程序中以毫秒为单位获取 Unix Epoch:

System.currentTimeMillis()

因此,您将如何获得 30 分钟前的值?

考虑使用数学。一秒有1000毫秒,一分钟有60秒。因此:

System.currentTimeMillis() - 30 * 60 * 1000

java.time

使用 java.time,现代日期时间 API,您无需自己执行任何计算即可完成。

演示:

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        long millisNow = System.currentTimeMillis();
        Instant instantNow = Instant.ofEpochMilli(millisNow);
        Instant instant30MinsAgo = instantNow.minus(30, ChronoUnit.MINUTES);
        long millis30MinsAgo = instant30MinsAgo.toEpochMilli();
        // System.out.println(millis30MinsAgo);

        // In a single command
        long millisThrityMinsAgo = Instant.ofEpochMilli(System.currentTimeMillis())
                                    .minus(30, ChronoUnit.MINUTES)
                                    .toEpochMilli();
        
        // System.out.println(millisThrityMinsAgo);
    }
}

通过下面的代码,可以不使用System.currentTimeMillis()获取当前时刻:

Instant.now()

因此,您也可以通过以下代码获取 30 分钟前的 Unix Epoch 毫秒数:

Instant.now().minus(30, ChronoUnit.MINUTES).toEpochMilli()

详细了解 java.timemodern date-time API* from Trail: Date Time


* 无论出于何种原因,如果您必须坚持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