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
.
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.
MM/DD/YYYY - American style Gregorian date format. DD/MM/YYYY - European style Gregorian date format. YYYY/MM/DD - Sortable style Gregorian date format.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With