How to initialize Gregorian calendar with date as YYYY-MM-DD format?

后端 未结 2 1637
北海茫月
北海茫月 2021-01-28 08:49

I have a class which contains a variable

private GregorianCalendar cal;

Now I want to initialize it with a date in yyyy-mm-dd

2条回答
  •  逝去的感伤
    2021-01-28 09:20

    You can try to use SimpleDateFormat for example :

    GregorianCalendar cal = new GregorianCalendar();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    format.setCalendar(cal);
    String result = format.format(cal.getTime());
    System.out.println(result);//today is 2017-05-25
    

    To convert String to GregorianCalendar :

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
    Date date = format.parse("2017-05-25T14:36:52+03:00");
    GregorianCalendar cal2 = new GregorianCalendar();
    cal2.setTime(date);
    

提交回复
热议问题