javadatedatetimecalendarsimpledateformat

Convert String to Calendar Object in Java


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!


Solution

  • Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
    

    note: set Locale according to your environment/requirement


    See Also