java calendar 设置小时,如何为java.util.Calendar设置为在未来的特定时间段

I'm using Java's calendar to set an alarm at a specific date and time. I know how to make this work when the user selects a specific date and time. For example, if the user wants to set an alarm on July 17th, 2013 at 10:45AM, I'm using the following code:

//Get the calendar instance.

Calendar calendar = Calendar.getInstance();

//Set the time for the notification to occur.

calendar.set(Calendar.YEAR, 2013);

calendar.set(Calendar.MONTH, 6);

calendar.set(Calendar.DAY_OF_MONTH, 17);

calendar.set(Calendar.HOUR_OF_DAY, 10);

calendar.set(Calendar.MINUTE, 45);

calendar.set(Calendar.SECOND, 0);

All of the above code works really well when I want to set an alarm at a specific date and time. My question is, how can I set a calendar instance where the user user wants an alarm to go off 20 minutes from the current date and time? So if the current time is 6:50PM, I need the alarm to go off at 7:10PM. How can I set this programmatically?

I tried to get the current date and time via the Java.util.calendar's built-in methods and tried adding 20 minutes to the Calendar.MINUTE variable. However, I don't think this will do the trick if the current time is less than 20mins away from midnight (the date will change), or 20mins away from another hour (the hour will change). How can I get around this problem? Thanks for all your help!

解决方案

You want to look at calendar.add , it will increment the next field if you get overflow.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值