Reputation: 54332
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?
Upvotes: 3
Views: 23141
Reputation: 11
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
Upvotes: 0
Reputation:
You have to use Calendar
:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
date = cal.getTime();
Upvotes: 11
Reputation: 240996
Calendar cal = Calendar.getInstance();
cal.setTime(setYourTimeHereInDateObj);
cal.add(Calendar.HOUR, 1);
Date timeAfterAnHour = cal.getTime();
//now format this time
See
Upvotes: 5
Reputation: 18662
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).
Upvotes: 2
Reputation: 12367
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
Upvotes: 6