Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a certain amount of time to a current time and write it

Tags:

android

time

add

I'm using:

Calendar c = Calendar.getInstance();

with which i get a current time,

String sHour = c.get(Calendar.HOUR_OF_DAY)
String sMinute = c.get(Calendar.MINUTE)

What i need is to add e.g. 1 Hour 10 Minutes - store it in a variable and also Substract let's say 10 minutes and save that as an another variable. (I need to use them both in a TextView)

I've seen the add(); method in Android documentation but I can't seem to understand how it works. Thanks

like image 356
jackal Avatar asked Aug 30 '11 18:08

jackal


2 Answers

The code you've posted won't compile, as Calendar.get() doesn't return a string. You should also note that calendar is mutable - it's not like each call to add returns a new calendar. So you'll need to create a new instance each time you want a separate variable for a different value. For example:

Calendar now = Calendar.getInstance();

Calendar tmp = (Calendar) now.clone();
tmp.add(Calendar.HOUR_OF_DAY, 1);
tmp.add(Calendar.MINUTE, 10);
Calendar nowPlus70Minutes = tmp;

tmp = (Calendar) now.clone();
tmp.add(Calendar.MINUTE, -10);
Calendar nowMinus10Minutes = tmp;

If at all possible, I'd strongly recommend that you use Joda Time instead of Calendar/Date - it's a far superior API. You may want to trim the time zones included with it, however, so that it's faster to get started and less overhead in your apk.

like image 172
Jon Skeet Avatar answered Nov 17 '22 04:11

Jon Skeet


You can simply call System.currentTimeMillis() + INTERVAL.

Where INTERVAL is the interval in milliseconds (for example:

public static final long INTERVAL = 1000 * 60 * 60 * 24; // 1 day
like image 44
IncrediApp Avatar answered Nov 17 '22 06:11

IncrediApp