3

I have my time in the below 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, is it possible to add one hour to this time format?

Andro Selva
  • 53,910
  • 52
  • 193
  • 240

5 Answers5

11

You have to use Calendar:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
date = cal.getTime();
6

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

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

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

jabal
  • 11,987
  • 12
  • 51
  • 99
5
Calendar cal = Calendar.getInstance();
cal.setTime(setYourTimeHereInDateObj);
cal.add(Calendar.HOUR, 1);
Date timeAfterAnHour = cal.getTime();
//now format this time 

See

jmj
  • 237,923
  • 42
  • 401
  • 438
  • Could I use GregorianCalendar in Android? Like so: Calendar mcalendar = new GregorianCalendar(); mcalendar.add(Calendar.HOUR_OF_DAY, 1); – user20191130 Dec 08 '20 at 01:47
2

If you can't use Jabal's suggestion (i.e. you are not allowed to use non-JDK libraries), you can use this:

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

If by a chance you are looking for time zone conversion, you can simply assign one to your formatter, it would work faster:

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. Unless you have a good reason not to, you should use the one that is valid for end user's Locale (DateFormat df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);). Otherwise you create i18n defect (who cares, I know).

Paweł Dyda
  • 18,366
  • 7
  • 57
  • 79
  • I didn't think that way but I like the way you do. Is it faster than using Calendar ? You said that sometimes you can't use Calendar, why ? –  May 16 '11 at 08:49
  • I don't know if it is faster than Calendar (I can't issue such a strong statement without using profiler). Also, I didn't say that I can't use Calendar, all I meant there are some platforms that simply do not contain Calendar implementation (for example Google App Engine). In that case developers have to stick to Date. That is unless GAE allows you to upload ICU for example – Paweł Dyda May 16 '11 at 08:55
0

If you're confused what to use between Calendar.HOUR & Calendar.HOUR_OF_DAY. go with Calendar.MILLISECOND

val nextHour: Date = Calendar.getInstance().also {
        it.time = Date() // set your date time here
    }.also {
        it.add(Calendar.MILLISECOND, 1 * 60 * 60 * 1000) // 1 Hour
    }.time