Java System.currentTimeMillis() 对于给定日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/632884/
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
System.currentTimeMillis() for a given date?
提问by yanchenko
Since java.util.Date is mostly deprecated, what's the right way to get a timestamp for a given date, UTC time? The one that could be compared against System.currentTimeMillis()
.
由于 java.util.Date 大多已弃用,获取给定日期(UTC 时间)的时间戳的正确方法是什么?可以与System.currentTimeMillis()
.
采纳答案by David Sykes
Using the Calendarclass you can create a time stamp at a specific time in a specific timezone. Once you have that, you can then get the millisecond time stamp to compare with:
使用Calendar类,您可以在特定时区的特定时间创建时间戳。一旦你有了它,你就可以得到毫秒时间戳来比较:
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_MONTH, 10);
// etc...
if (System.currentTimeMillis() < cal.getTimeInMillis()) {
// do your stuff
}
edit: changed to use more direct method to get time in milliseconds from Calendar instance. Thanks Outlaw Programmer
编辑:更改为使用更直接的方法从 Calendar 实例获取时间(以毫秒为单位)。感谢亡命之徒程序员
回答by TofuBeer
回答by Daniel Schneller
The "official" replacement for many things Date was used for is Calendar. Unfortunately it is rather clumsy and over-engineered. Your problem can be solved like this:
Date 用于许多事物的“官方”替代品是 Calendar。不幸的是,它相当笨拙且设计过度。你的问题可以这样解决:
long currentMillis = System.currentTimeMillis();
Date date = new Date(currentMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long calendarMillis = calendar.getTimeInMillis();
assert currentMillis == calendarMillis;
Calendars can also be initialized in different ways, even one field at a time (hour, minute, second, etc.). Have a look at the Javadoc.
日历也可以用不同的方式初始化,甚至一次一个字段(小时、分钟、秒等)。看看Javadoc。
回答by jfpoilpret
Although I didn't try it myself, I believe you should take a look at the JODA-Time project (open source) if your project allows external libs. AFAIK, JODA time has contributed a lot to a new JSR (normally in Java7) on date/time.
虽然我自己没有尝试过,但我相信如果你的项目允许外部库,我相信你应该看看JODA-Time项目(开源)。AFAIK,JODA 时间对日期/时间的新 JSR(通常在 Java7 中)做出了很大贡献。
Many people claim JODA time is the solution to all java.util.Date/Calendar problems;-)
许多人声称 JODA 时间是所有 java.util.Date/Calendar 问题的解决方案;-)
Definitely worth a try.
绝对值得一试。