如何以秒为单位获取当前UTC时间 [英] How to get the current UTC time in seconds

查看:503
本文介绍了如何以秒为单位获取当前UTC时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an application, which needs to compare the time in seconds.

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

I want to know how to get the current UTC time in seconds.

有人可以举一个例子吗?如何用Java做到这一点?

Can some one post an example of it how can we do this in Java?

推荐答案

您可以使用它来使时区传入您想回到的时区

You can use this to get timezone passing in timezone you want time back in

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

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

Then you can call whatever you want on the calendar object

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));

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

Below example to compare two calendars in seconds

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");

这篇关于如何以秒为单位获取当前UTC时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆