I am new to Java, usually work with PHP.
I am trying to convert this string:
Mon Mar 14 16:02:37 GMT 2011
Into a Calendar Object so that I can easily pull the Year and Month like this:
String yearAndMonth = cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH);
Would it be a bad idea to parse it manually? Using a substring method?
Any advice would help thanks!
Well, I think it would be a bad idea to replicate the code which is already present in classes like
SimpleDateFormat
.On the other hand, personally I'd suggest avoiding
Calendar
andDate
entirely if you can, and using Joda Time instead, as a far better designed date and time API. For example, you need to be aware thatSimpleDateFormat
is not thread-safe, so you either need thread-locals, synchronization, or a new instance each time you use it. Joda parsers and formatters are thread-safe.Parse a time with timezone,
Z
in pattern is for time zoneOutput: it will return the UTC time
If we don't set the time zone in pattern like
yyyy-MM-dd'T'HH:mm:ss
.SimpleDateFormat
will use the time zone which have set inSetting
Simple method:
Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.
tl;dr
The modern approach uses the java.time classes.
Avoid legacy date-time classes
The modern way is with java.time classes. The old date-time classes such as
Calendar
have proven to be poorly-designed, confusing, and troublesome.Define a custom formatter to match your string input.
Parse as a
ZonedDateTime
.You are interested in the year and month. The java.time classes include
YearMonth
class for that purpose.You can interrogate for the year and month numbers if needed.
But the
toString
method generates a string in standard ISO 8601 format.Put this all together.
Dump to console.
Live code
See this code running in IdeOne.com.
Conversion
If you must have a
Calendar
object, you can convert to aGregorianCalendar
using new methods added to the old classes.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.SimpleDateFormat
is great, just note thatHH
is different fromhh
when working with hours.HH
will return 24 hour based hours and hh will return 12 hour based hours.For example, the following will return 12 hour time:
While this will return 24 hour time: