Add H:M:S value on DateTime field

不羁岁月 提交于 2019-12-13 01:34:54

问题


How to add HOURS:MINUTES:SECONDS value on DateTime field?

On example I want in my field which contains dimetime value to add (sum) with string value which contains value in HH:MM:SECONDS.

ReportDate is 2013-01-01 10:00:00 Value to add is :120:34:29

So result should be: 2013-01-06 10:34:00

I tried with:

GregorianCalendar c = new GregorianCalendar();
c.setTime(reportDate);
String toAdd='120:34:29';
c.add(Calendar.HOUR, toAdd);
java.util.Date targetFinish = c.getTime();
SystemOutPrintln(targetFinish.toString()); 

So problematic row is c.add(Calendar.HOUR, toAdd); How to add these value? I want to do it over Gregorian Calendar. And want to have in SysOut that new value; Thank you


回答1:


GregorianCalendar c = new GregorianCalendar();
c.setTime(reportDate);

String[] toAdd = "120:34:29".split(":");

int hours = Integer.parseInt(toAdd[0]);
int mins = Integer.parseInt(toAdd[1]);
int secs = Integer.parseInt(toAdd[2]);

c.add(Calendar.SECOND, secs);
c.add(Calendar.MINUTE, mins);
c.add(Calendar.HOUR, hours);

java.util.Date targetFinish = c.getTime();

SystemOutPrintln(targetFinish.toString());



回答2:


You can parse text into hours, minutes and seconds and add them like -

String[] time ="120:34:29".split(":");

c.add(Calendar.HOUR, Integer.parseInt(time[0]));
c.add(Calendar.MINUTE, Integer.parseInt(time[1]));
c.add(Calendar.SECOND, Integer.parseInt(time[2]));


来源:https://stackoverflow.com/questions/16603500/add-hms-value-on-datetime-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!