英文:
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("yyyy-MM-dd hh:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Some/Location"));
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论