Get day, month and year separately using SimpleDateFormat

前端 未结 8 864
無奈伤痛
無奈伤痛 2021-02-08 19:45

I have a SimleDateFormat like this

SimpleDateFormat format = new SimpleDateFormat(\"MMM dd,yyyy  hh:mm\");
String date = format.format(Date.parse(p         


        
8条回答
  •  孤城傲影
    2021-02-08 20:03

    Wow, SimpleDateFormat for getting string parts? It can be solved much easier if your input string is like "Jan,23,2014":

    String input = "Jan,23,2014";
    String[] out = input.split(",");
    System.out.println("Year = " + out[2]);
    System.out.println("Month = " + out[0]);
    System.out.println("Day = " + out[1]);
    

    Output:

    Year = 2014
    Month = Jan
    Day = 23
    

    But if you really want to use SimpleDateFormat because of some reason, the solution will be the following:

    String input = "Jan,23,2014";
    SimpleDateFormat format = new SimpleDateFormat("MMM,dd,yyyy");
    Date date = format.parse(input);
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
    calendar.setTime(date);
    System.out.println(calendar.get(Calendar.YEAR));
    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
    System.out.println(new SimpleDateFormat("MMM").format(calendar.getTime()));
    

    Output:

    2014
    23
    Jan
    

提交回复
热议问题