Date のコードはミリ秒ではありません ;-) しかし、次に getTime() を呼び出すと、ミリ秒単位で時間が取得されます。
次のアラームの時間に基づいて、寝る時間を計算するために小さなアプリでこのコードを使用しています。これは、さまざまなアプローチを 2 時間試行して作成されたものであるため、最適化されている可能性があります。
public static Date getNextAlarm(Context context) {
// let's collect short names of days :-)
DateFormatSymbols symbols = new DateFormatSymbols();
// and fill with those names map...
Map<String, Integer> map = new HashMap<String, Integer>();
String[] dayNames = symbols.getShortWeekdays();
// filing :-)
map.put(dayNames[Calendar.MONDAY],Calendar.TUESDAY);
map.put(dayNames[Calendar.TUESDAY],Calendar.WEDNESDAY);
map.put(dayNames[Calendar.WEDNESDAY],Calendar.THURSDAY);
map.put(dayNames[Calendar.THURSDAY],Calendar.FRIDAY);
map.put(dayNames[Calendar.FRIDAY],Calendar.SATURDAY);
map.put(dayNames[Calendar.SATURDAY],Calendar.SUNDAY);
map.put(dayNames[Calendar.SUNDAY],Calendar.MONDAY);
// Yeah, knowing next alarm will help.....
String nextAlarm = Settings.System.getString(context.getContentResolver(),Settings.System.NEXT_ALARM_FORMATTED);
// In case if it isn't set.....
if ((nextAlarm==null) || ("".equals(nextAlarm))) return null;
// let's see a day....
String nextAlarmDay = nextAlarm.split(" ")[0];
// and its number....
int alarmDay = map.get(nextAlarmDay);
// the same for day of week (I'm not sure why I didn't use Calendar.get(Calendar.DAY_OF_WEEK) here...
Date now = new Date();
String dayOfWeek = new SimpleDateFormat("EE", Locale.getDefault()).format(now);
int today = map.get(dayOfWeek);
// OK, so let's calculate how many days we have to next alarm :-)
int daysToAlarm = alarmDay-today;
// yep, sometimes it will be negtive number so add 7.
if (daysToAlarm<0) daysToAlarm+=7;
// Now we will build date, and parse it.....
try {
Calendar cal2 = Calendar.getInstance();
String str = cal2.get(Calendar.YEAR)+"-"+(cal2.get(Calendar.MONTH)+1)+"-"+(cal2.get(Calendar.DAY_OF_MONTH));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-d hh:mm");
cal2.setTime(df.parse(str+nextAlarm.substring(nextAlarm.indexOf(" "))));
cal2.add(Calendar.DAY_OF_YEAR, daysToAlarm);
// and return it
return cal2.getTime();
} catch (Exception e) {
}
// in case if we cannot calculate...
return null;
}