0
    SimpleDateFormat dateFormat = new 
    SimpleDateFormat("yyyyMMdd");//20180603
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date dateResult = dateFormat.parse(inputString);


    Calendar cal = Calendar.getInstance();
    cal.setTime(dateResult);
    cal.setTimeZone( TimeZone.getTimeZone("GMT"));
    System.out.println(cal.get(Calendar.YEAR)); // 2018
    System.out.println(cal.get(Calendar.MONTH)); //05 ?? (instead of 96)
    System.out.println(cal.get(Calendar.DAY_OF_MONTH)); // 03 

Strangely, when I'm converting a string to date using the above method, the output is 20180503 instead of 2018063. Couldn't find out why this month mismatch occurs. Any suggestions would be appreciated.

Kans
  • 382
  • 3
  • 17
  • 1
    I think you messed up some numbers in your question. However in Java Calendar, the months start with 0, which means january is 0, februrary 1 etc. https://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar – Ian Fako Mar 08 '18 at 09:59
  • your input has to be 20180703 as @IanFako said already in java calendar month counts start with 0. hence it shows a month lesse than expected. – Amit Kumar Lal Mar 08 '18 at 10:01
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It also solves your problem: `LocalDate.parse("20180603", DateTimeFormatter.BASIC_ISO_DATE).getMonthValue()` will give 6 since the modern API numbers months the same way as humans do. – Ole V.V. Mar 08 '18 at 10:39
  • 1
    Thanks for the clarifications. Will use LocalDate parser instead of SimpleDateFormat. – Kans Mar 09 '18 at 05:28

0 Answers0