是否有更好/更简单的方法来构建今天早上6点的LocalDateTime
对象?
LocalDateTime todayAt6 = LocalDateTime.now().withHour(6).withMinute(0).withSecond(0).withNano(0);
不知何故,当我想说的只是now().withHours()
时,我不喜欢处理分钟/秒/纳米。
答案 0 :(得分:30)
LocalDate
有各种重载的atTime
方法,例如this one,它有两个参数(一天一小时和一小时):
LocalDateTime todayAt6 = LocalDate.now().atTime(6, 0);
答案 1 :(得分:5)
另一种选择(特别是如果您想要更改现有的LocalDateTime
)是使用with()
method。
它接受TemporalAdjuster
作为参数。根据{{3}},将LocalTime
传递给此方法可以完全满足您的需求:
类LocalDate和LocalTime实现TemporalAdjuster,因此此方法可用于更改日期,时间或偏移量:
result = localDateTime.with(date);
result = localDateTime.with(time);
所以,代码将是:
LocalDateTime todayAt6 = LocalDateTime.now().with(LocalTime.of(6, 0));
答案 2 :(得分:3)
接受的答案很好。您也可以创建自己的clock来执行此操作:
Clock clock = Clock.tick(Clock.systemDefaultZone(), Duration.ofHours(1));
LocalDateTime dt = LocalDateTime.now(clock);
如果重复使用,这可能是一个有用的选项,因为时钟可以存储在静态变量中:
public static final Clock CLOCK = Clock.tick(Clock.systemDefaultZone(), Duration.ofHours(1));
LocalDateTime dt = LocalDateTime.now(CLOCK);
答案 3 :(得分:2)
func setNotifications(date: Date, forMonth: Bool) {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
if forMonth == true {
let content = UNMutableNotificationContent()
content.title = ""
content.body = "Here is some nice content."
content.sound = UNNotificationSound.default()
let triggerDate = Calendar.current.dateComponents([.day], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let request = UNNotificationRequest(identifier: "MonthNotification", content: content, trigger: trigger)
center.add(request, withCompletionHandler: nil)
}
}
}
}
的替代方案是:
LocalDate.now().atTime(6, 0)
答案 4 :(得分:1)
可行
LocalDateTime.now().withHour(3).withMinute(0).withSecond(0);