简体   繁体   中英

How to convert Date/Time from Long(millisecodns) to RFC-822 format in Java

I have time in milliseconds I need to convert it to RFC-822 format. Is there generic Java library that can I use? What is the best practice of doing it?

Example time in milliseconds: 1440612000000 Time in RFC-822: Wed, 02 Oct 2002 08:00:00 EST

Thanks in advance.

You can use the calendar class included in 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);

Then you can just build a string out of the values. Eg :

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);

will print: Wed, 02 Oct 2002

Use the 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));

As an example, with 1440612000000L outputs Wed, 26 Aug 2015 13:00:00 EST .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM