4

我已经阅读了所有文档,似乎没有太多可以真正解释日期功能或缺少的内容。

我正在尝试实现 AlarmManger,它需要以毫秒 (ms) 为单位的触发时间。为了测试,我用了当前时间并增加了 5 秒,这很好。

// get a Calendar object with current time
 Calendar cal = Calendar.getInstance();
 // add 5 minutes to the calendar object
 cal.add(Calendar.SECOND, 5);

如果我有日期和时间,我将如何获得那个时间的毫秒。

喜欢“2011 年 3 月 2 日 08:15:00”

我如何把它变成毫秒?

4

2 回答 2

14

使用此方法。

例子:

2011 年 3 月 2 日 08:15:00 的方法调用

D2MS( 3, 2, 2011, 8, 15, 0);

方法

public long D2MS(int month, int day, int year, int hour, int minute, int seconds) { 
    Calendar c = Calendar.getInstance();
    c.set(year, month, day, hour, minute, seconds);

    return c.getTimeInMillis();  
} 
于 2011-03-02T02:09:16.860 回答
3

使用 AlarmManager 时,您有两个设置警报的选择 - 第一个是以毫秒为单位的设备重新启动后的时间(不理解该选项),或者,如果您想要一个“绝对”时间,那么您需要以毫秒为单位提供 UTC 时间.

我认为这应该可行 - 我过去做过类似的事情......

public long getUtcTimeInMillis(String datetime) {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date date = sdf.parse(datetime);

    // getInstance() provides TZ info which can be used to adjust to UTC
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    // Get timezone offset then use it to adjust the return value
    int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
    return cal.getTimeInMillis() + offset;
}

我个人建议尝试使用非本地化格式,例如,yyyy-MM-dd HH:mm:ss如果您想满足全球用户的需求,您使用的任何日期/时间字符串。

ISO 8601 国际标准是yyyy-MM-dd HH:mm:ss.SSSZ,但我通常不会走那么远。

于 2011-03-02T03:31:33.360 回答