adding hours in date time format java

后端 未结 3 2160
小鲜肉
小鲜肉 2021-01-06 12:48
SimpleDateFormat parser = new SimpleDateFormat(\"HH:mm\");
Date time1 = parser.parse(\"7:30\");

Now if I want to add 2 more hours to time1

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 13:06

    Convert java.util.Date into java.util.Calendar Object and use Calendar.add() method to add Hours

    SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
    Date time1 = parser.parse("7:30");
    Calendar cal =Calendar.getInstance();
    cal.setTime(time1);
    cal.add(Calendar.Hour_Of_Day, 2);
    time1 =cal.getTime();
    System.out.println(parser.format(time1));//returns 09:30
    

提交回复
热议问题