Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to GregorianCalendar

I have a string from an email header, like Date: Mon, 27 Oct 2008 08:33:29 -0700. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?

And for the fastest ones -- this is not going to work properly:

SimpleDateFormat format = ... // whatever you want
Date date = format.parse(myString)
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date)

because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return -7 * milisInAnHour.

like image 298
Marcin Avatar asked Oct 27 '08 16:10

Marcin


People also ask

How to convert string to GregorianCalendar in java?

Use SimpleDateFormat to parse the date and then assign it to a Calendar . DateFormat df = new SimpleDateFormat("dd MM yyyy"); Date date = df. parse("02 26 1991"); Calendar cal = Calendar. getInstance(); cal.

What is Gregorian date format example?

MM/DD/YYYY - American style Gregorian date format. DD/MM/YYYY - European style Gregorian date format. YYYY/MM/DD - Sortable style Gregorian date format.


1 Answers

I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually.

http://joda-time.sourceforge.net/

So anyway, if Joda Time is an option, something like this should work:

DateTimeFormatter formatter =
    DateTimeFormat.forPattern("your pattern").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("your input");
GregorianCalendar cal = dateTime.toGregorianCalendar();

I hope this helps.

like image 97
Jack Leow Avatar answered Sep 20 '22 23:09

Jack Leow