how to convert string into time format and add two hours

后端 未结 9 1111
轻奢々
轻奢々 2020-12-13 05:04

I have the following requirement in the project.

I have a input field by name startDate and user enters in the format YYYY-MM-DD HH:MM:SS.

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 05:34

    Try this one, I test it, working fine

    Date date = null;
    String str = "2012/07/25 12:00:00";
    DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    date = formatter.parse(str);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR, 2);
    System.out.println(calendar.getTime());  // Output : Wed Jul 25 14:00:00 IST 2012
    

    If you want to convert in your input type than add this code also

    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    str=formatter.format(calendar.getTime());
    System.out.println(str);  // Output : 2012-07-25 14:00:00
    

提交回复
热议问题