Java 如何以秒为单位获取当前的 UTC 时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19314404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:01:13  来源:igfitidea点击:

How to get current UTC timestamp in seconds

javatimestamp

提问by kreya

How to get current time-stamp in UTC/GMT and then How to convert this time-stamp into seconds ? Itry this but its thrw exception

如何在 UTC/GMT 中获取当前时间戳,然后如何将此时间戳转换为秒?Ittry this 但它的 thrw 异常

    SimpleDateFormat sdfu  = new SimpleDateFormat("yyyy-MM-dd kk:mm");
    Date udate = sdfu.parse(dateAndTimeUTC);
    long timeInMillisSinceEpoch123 = udate.getTime(); 
    long durationinSeconds2 = timeInMillisSinceEpoch123 / 1000;
    System.out.println("Time in Seconds UTC: " + durationinSeconds2);

Is there any better way to convert UTC/GMT time-stamp into seconds?

有没有更好的方法将 UTC/GMT 时间戳转换为秒?

回答by Dat Nguyen

get current seconds system long timestamp = System.currentTimeMillis() / 1000;

获取当前秒系统 long timestamp = System.currentTimeMillis() / 1000;

回答by Jing DU

I have realised it as below:

我已经意识到它如下:

long currentTS = Long.valueOf(String.valueOf(System.currentTimeMillis()/1000));

long currentTS = Long.valueOf(String.valueOf(System.currentTimeMillis()/1000));

Another way is to truncate last three digits from System.currentTimeMillis():

另一种方法是截断 System.currentTimeMillis() 的最后三位数字:

String currentTSstr = String.valueOf(System.currentTimeMillis()); long currentTS = Long.valueOf(currentTSstr.substring(0, currentTSstr.length()-3));

String currentTSstr = String.valueOf(System.currentTimeMillis()); long currentTS = Long.valueOf(currentTSstr.substring(0, currentTSstr.length()-3));

回答by yuen26

With Java 8+, you can use:

使用 Java 8+,您可以使用:

Instant.now().getEpochSecond()