如何获取 UTC/GMT 中的当前时间戳,然后如何将此时间戳转换为秒?尝试一下,但它抛出异常
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);
有没有更好的方法将UTC/GMT时间戳转换为秒?
获取当前秒系统
long timestamp = System.currentTimeMillis() / 1000;
使用 Java 8+,您可以使用:
Instant.now().getEpochSecond()
更详细的版本,可以推广到任何时区:
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of ( "UTC" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant, zoneId );
ZonedDateTime zdtMonthEarlier = zdt.minus ( 1 , ChronoUnit.MONTHS );
long t = zdtMonthEarlier.toEpochSecond();
System.out.println( "Time in Seconds At One Month Ago: " + Long.valueOf(t) );