Using GregorianCalendar with SimpleDateFormat

后端 未结 5 1939
渐次进展
渐次进展 2020-12-03 04:45

So, I\'ve been racking my brain over this (should-be) simple exercise to make the program turn a date string into a GregorianCalendar object, format it, and ret

5条回答
  •  再見小時候
    2020-12-03 05:16

    1. You are putting there a two-digits year. The first century. And the Gregorian calendar started in the 16th century. I think you should add 2000 to the year.

    2. Month in the function new GregorianCalendar(year, month, days) is 0-based. Subtract 1 from the month there.

    3. Change the body of the second function as follows:

          String dateFormatted = null;
          SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
          try {
              dateFormatted = fmt.format(date);
          }
          catch ( IllegalArgumentException e){
              System.out.println(e.getMessage());
          }
          return dateFormatted;
      

    After debugging, you'll see that simply GregorianCalendar can't be an argument of the fmt.format();.

    Really, nobody needs GregorianCalendar as output, even you are told to return "a string".

    Change the header of your format function to

    public static String format(final Date date) 
    

    and make the appropriate changes. fmt.format() will take the Date object gladly.

    1. Always after an unexpected exception arises, catch it yourself, don't allow the Java machine to do it. This way, you'll understand the problem.

提交回复
热议问题