如何获取不同时区的TimeInMillis

huangapple go评论68阅读模式
英文:

How to get TimeInMillis for different TimeZone

问题

我已经厌倦了对如此简单的问题进行搜索。
请不要建议我使用Joda Time或Java 8,我想使用简单的*java.time.*并且我使用的是Java 7。

我只想获取特定时区的currentTimeInMillis,所有我找到的示例都只是提供了如何使用以下代码来打印实际日期的解决方案:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Some/Location"));

但我不想要日期,我只想要实际时间戳

非常感谢

英文:

I'm tired of searching about so simple question.<br>
Please don't suggest me using Joda Time or Java 8, I want to use the simple java.time.* and I have Java 7.

I just want to get the currentTimeInMillis for some specific time zone, all examples I found just providing me a solution how to print the actual date by using

SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-MM-dd hh:mm:ss&quot;);
sdf.setTimeZone(TimeZone.getTimeZone(&quot;Some/Location&quot;));

But I don't want the date, I just want the actual timestamp.

Thanks a lot

答案1

得分: 4

无论你身在何处,System.currentTimeMillis() 都会始终返回自1970年1月1日午夜(UTC)以来的毫秒数,也就是说,如果你在伦敦、新德里和纽约的 JVM 上同时执行以下代码,结果将会相同,因为 System.currentTimeMillis() 不受时区影响。

public class Main {
    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }
}

因此,如果你的应用程序和另一个时区中运行的应用程序都将时间戳捕获为 System.currentTimeMillis() 的值,你可以放心比较它们的值,而不用担心时区差异。

英文:

No matter which part of the world you are in, System.currentTimeMillis() will always return you no. of milliseconds from midnight, January 1, 1970 UTC i.e. if you execute the following code at the same time on the JVMs located in London, New Delhi and New York, the result will be the same because System.currentTimeMillis() is independent of time-zone.

public class Main {
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
	}
}

Thus, if your application and the application running in another time-zone, both are capturing the timestamp as the value of System.currentTimeMillis() you can safely compare their values without worrying about the differences in the time-zone.

huangapple
  • 本文由 发表于 2020年9月30日 23:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64140708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定