0

我需要使用自定义时间获取实际日期,因此我创建了以下代码:

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());

Calendar output = Calendar.getInstance();
output.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 1, 0);
output.getTime();

我希望它有效,但它似乎有点复杂。

有没有其他方法可以获取自定义时间的日期?

4

4 回答 4

3

还有其他方法可以使用自定义时间获取日期吗?

我个人会改用Joda Time

// Ideally use an injectable clock...
LocalDate today = new LocalDate();
// If this is effectively constant, extract it to a final static field
LocalTime time = new LocalTime(1, 0);

// Or use toDateTime(...) depending on what you're trying to accomplish
LocalDateTime todayAtTime = today.toLocalDateTime(time);

Joda Time 的APIjava.util.{Date, Calendar}

于 2013-03-21T15:44:26.557 回答
0
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.getTime()
于 2013-03-21T15:47:49.970 回答
0

那这个呢 :

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, your_custom_hour);
your_custom_hour : 0-23
于 2013-03-21T15:48:03.433 回答
0

除了使用 Joda 时间,我会稍微清洁一点:

 int hour = 1;
 Calendar cal = Calendar.getInstance();
 cal.set(Calendar.HOUR, hour);
 cal.set(Calendar.MINUTE, 0);
 cal.set(Calendar.SECOND, 0);
 cal.set(Calendar.MILLISECOND, 0);

Calendar.getInstance()无论如何都返回当前日期和时间,所以setTime(new Date())没有必要。

于 2013-03-21T15:51:39.937 回答