How to add an hour to my time

I have time in the lower format, and I use this value to set the text of my button.

String strDateFormat = "HH:mm: a";
SimpleDateFormat sdf ;
 sdf = new SimpleDateFormat(strDateFormat);
startTime_time_button.setText(sdf.format(date));

Now my question is: can I add one hour to this time format?

+3
source share
4 answers

I think the best and easiest way is to use Apache Commons Lang:

Date incrementedDate = DateUtils.addHour(startDate, 1);

http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/time/DateUtils.html

+6
source

You should use Calendar:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
date = cal.getTime();
+8
source
Calendar cal = Calendar.getInstance();
cal.setTime(setYourTimeHereInDateObj);
cal.add(Calendar.HOUR, 1);
Date timeAfterAnHour = cal.getTime();
//now format this time 

+3

Jabal- (.. , JDK), :

long hour = 3600 * 1000; // 3600 seconds times 1000 milliseconds
Date anotherDate = new Date(date.getTime() + hour);

, , :

TimeZone timeZone = TimeZone.getTimeZone("UTC"); // put your time zone instead of UTC
sdf.setTimeZone(timeZone);

BTW. Hard coding date format is not the best of ideas. If you have no reason for this, you should use the one that is valid for the user Locale ( DateFormat df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);). Otherwise, you create an i18n defect (who cares, I know).

+2
source

All Articles