如何在Java中将日期/时间从Long(millisecodns)转换为RFC-822格式

时间:2015-08-26 18:33:38

标签: java milliseconds rfc822

我有时间以毫秒为单位,我需要将其转换为RFC-822格式。 是否可以使用通用Java库? 这样做的最佳做法是什么?

以毫秒为单位的示例时间: 1440612000000 RFC-822的时间:星期三,2002年10月2日08:00:00 EST

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用Java中包含的日历类:

Calendar calendar = Calendar.getInstance();
// set time in millis
calender.setTimeInMillis(millis);

int year       = calendar.get(Calendar.YEAR);
int month      = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); 
int dayOfWeek  = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);

int hour       = calendar.get(Calendar.HOUR);        // 12 hour clock
int hourOfDay  = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute     = calendar.get(Calendar.MINUTE);
int second     = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);

System.out.println(sdf.format(calendar.getTime()));

System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);

System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);

然后你可以用值构建一个字符串。例如。 :

String s = calender.getDisplayName(Calender.DAY_OF_WEEK, Calender.SHORT, locale) + ", " + calender.get(Calender.DAY_OF_MONTH) + " " + calender.getDisplayName(Calender.MONTH, Calender.SHORT, locale) + " " + calender.get(Calender.YEAR);

将打印:Wed, 02 Oct 2002

答案 1 :(得分:1)

使用SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
dateFormat.setTimeZone(TimeZone.getTimeZone("EST")); //To use the EST time zone as in your example
dateFormat.format(new Date(timeInMiliseconds));

例如,1440612000000L输出Wed, 26 Aug 2015 13:00:00 EST