0

给定任务t = System.currentTimeMillis(),在过去的某个时间点累积,我如何在下午 12 点和下午 12 点之后获得与 t 同一天的毫秒?

4

3 回答 3

4

注意:这取决于时区。你可以这样做:

import static java.util.Calendar.*;

final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(yourValue);
cal.set(HOUR_OF_DAY, 12);
cal.set(MINUTE, 0);
cal.set(SECOND, 0);
cal.set(MILLISECOND, 0);
// cal.getTimeInMillis() contains the wanted day at 12pm
cal.add(DAY_OF_YEAR, 1);
// cal.getTimeInMillis() now contains the wanted day plus one at 12pm

但是帮自己一个忙并使用Joda Time,在这种情况下使用起来要容易得多:

final DateTime dayAt12pm = new DateTime(yourValue).toDateMidnight()
    .plusHours(12);
// dayAt12pm.getMillis() contains the wanted day at 12pm
// next day at 12pm: dayAt12pm.plusDays(1).getMillis()
于 2013-07-12T16:01:05.817 回答
2
//plug your "T" here.
long t = System.currentTimeMillis();

Date date = new Date(t);
Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

Calendar startOfDay = Calendar.getInstance();
startOfDay.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
startOfDay.set(Calendar.HOUR, 12);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MILLISECOND, 0);

Date startOfDayDate = startOfDay.getTime();
System.err.println("12PM on time t is " + startOfDayDate);

startOfDay.add(Calendar.HOUR, 24);
startOfDayDate = startOfDay.getTime();
System.err.println("12PM day after t is " + startOfDayDate);
于 2013-07-12T16:06:51.880 回答
0

一种方法是从中创建一个Date,然后使用 Calendar 类。

于 2013-07-12T16:03:11.313 回答