如何在Java中从公历转换为Unix时间? [英] How can I convert from Gregorian Calendar to Unix Time, in Java?
问题描述
我需要一种将GregorianCalendar对象转换为Unix时间(即很长)的方法.还需要一种将Unix时间(长)转换回GregorianCalendar对象的方法.有没有什么方法可以做到这一点?如果没有,那我该怎么办?任何帮助将不胜感激.
I am in need of a method to convert GregorianCalendar Object to Unix Time (i.e. a long). Also need a method to convert Unix Time (long) back to GregorianCalendar Object. Are there any methods out there that does this? If not, then how can I do it? Any help would be highly appreciated.
链接到GregorianCalendar类-> http ://download.oracle.com/javase/1.4.2/docs/api/java/util/GregorianCalendar.html
Link to GregorianCalendar Class --> http://download.oracle.com/javase/1.4.2/docs/api/java/util/GregorianCalendar.html
谢谢.
推荐答案
方法getTimeInMillis()
和setTimeInMillis(long)
将使您获得并设置时间(以毫秒为单位),该时间是unix时间乘以1000.手动调整,因为Unix时间不包括毫秒-仅秒.
The methods getTimeInMillis()
and setTimeInMillis(long)
will let you get and set the time in milliseconds, which is the unix time multiplied by 1000. You will have to adjust manually since unix time does not include milliseconds - only seconds.
long unixTime = gregCal.getTimeInMillis() / 1000;
gregCal.setTimeInMillis(unixTime * 1000);
旁边:如果您在应用程序中使用很多日期,尤其是在转换日期或使用多个时区时,我强烈建议使用
Aside: If you use dates a lot in your application, especially if you are converting dates or using multiple time zones, I would highly recommend using the JodaTime library. It is very complete and quite a bit more natural to understand than the Calendar system that comes with Java.
这篇关于如何在Java中从公历转换为Unix时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!