如何将 Java.util.calendar 设置为未来的特定时间段 [英] How to set Java.util.calendar to a specific time period in the future

查看:18
本文介绍了如何将 Java.util.calendar 设置为未来的特定时间段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java 的日历在特定日期和时间设置闹钟.当用户选择特定日期和时间时,我知道如何进行这项工作.例如,如果用户想在 2013 年 7 月 17 日上午 10:45 设置闹钟,我使用以下代码:

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);

当我想在特定日期和时间设置警报时,上述所有代码都非常有效.我的问题是,我如何设置一个日历实例,用户用户希望闹钟在当前日期和时间后 20 分钟响起?因此,如果当前时间是下午 6:50,我需要闹钟在晚上 7:10 响起.如何以编程方式设置?

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?

我尝试通过 Java.util.calendar 的内置方法获取当前日期和时间,并尝试将 20 分钟添加到 Calendar.MINUTE 变量.但是,如果当前时间距离午夜不到 20 分钟(日期会改变),或者距离另一个小时不到 20 分钟(小时会改变),我认为这不会奏效.我怎样才能解决这个问题?感谢您的所有帮助!

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!

推荐答案

你想看看 calendar.add ,如果溢出它会增加下一个字段.

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

http://developer.android.com/reference/java/util/日历.html

这篇关于如何将 Java.util.calendar 设置为未来的特定时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆