开发者

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

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开发者_StackOverflow中文版.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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜