如何获取当前 UTC 时间(以秒为单位)

2022-09-04 06:04:04

我有一个应用程序,它需要以秒为单位比较时间。

我想知道如何获取当前UTC时间(以秒为单位)。

有人可以发布一个例子,我们如何在Java中做到这一点?


答案 1

您可以使用它来获取您想要的时间返回的时区的时区

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 

然后,您可以在日历对象上调用所需的任何内容

System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));

下面的示例以秒为单位比较两个日历

Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

// Set the dates for calendars
cal1.set(2011, 1, 1);
cal2.set(2011, 2, 2);

// Get the represented date in milliseconds as a long
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();

// Calculate difference in milliseconds
long diff = milis2 - milis1;

// Calculate difference in seconds
long diffSecs = diff / 1000;

System.out.println("In seconds: " + diffSecs + " seconds");

推荐