您可以使用兼容性方法java.util.Date.toInstant(),操作该Instant 的时间,从而创建一个不同的Instant,然后通过Date.from(Instant instant) 转换回Date。
这是一个操作的示例方法:
public static Instant adjustTimeOfDay(Instant instant, String timeOfDay) {
// convert the instant to an offset-aware datetime object
OffsetDateTime deliveryOdt = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
/*
* provide a formatter that parses a time-of-day String.
* PLEASE NOT that this formatter is not very lenient,
* the String must be of the pattern "hh:mm a"
*/
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("hh")
.appendLiteral(':')
.appendPattern("mm")
.appendLiteral(' ')
.appendPattern("a")
.parseCaseInsensitive()
.toFormatter();
// parse that String to a LocalTime
LocalTime localTime = LocalTime.parse(timeOfDay, dtf);
/*
* create a new OffsetDateTime
* adding the new LocalTime to the old LocalDate at UTC
*/
OffsetDateTime adjustedOdt = OffsetDateTime.of(deliveryOdt.toLocalDate(),
localTime,
ZoneOffset.UTC);
return adjustedOdt.toInstant();
}
我在main 中使用过这样的:
public static void main(String[] args) {
/*
* instead of creating a Date,
* I directly use Instant here and parse your example String,
* so just use your deliveryDate.toInstant()
*/
String input = "2020-10-07T03:10:00Z";
Instant instant = Instant.parse(input);
// then take a time of day to be set
String timeOfDayUpdate = "07:20 AM";
Instant adjusted = adjustTimeOfDay(instant, timeOfDayUpdate);
System.out.println(input + " ==> " + OffsetDateTime.ofInstant(adjusted, ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_INSTANT));
}
创建了以下输出:
2020-10-07T03:10:00Z ==> 2020-10-07T07:20:00Z
编辑
您可以将该方法重写为
public static Date adjustTimeOfDay(Date date, String timeOfDay) {
// convert the date to an instant and the instant to an offset-aware datetime object
OffsetDateTime deliveryOdt = OffsetDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC);
// provide a formatter that parses a time-of-day String
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("hh")
.appendLiteral(':')
.appendPattern("mm")
.appendLiteral(' ')
.appendPattern("a")
.parseCaseInsensitive()
.toFormatter();
// parse that String to a LocalTime
LocalTime localTime = LocalTime.parse(timeOfDay, dtf);
/*
* create a new OffsetDateTime
* adding the new LocalTime to the old LocalDate at UTC
*/
OffsetDateTime adjustedOdt = OffsetDateTime.of(deliveryOdt.toLocalDate(),
localTime,
ZoneOffset.UTC);
// return a Date from the Instant you get out of the OffsetDateTime
return Date.from(adjustedOdt.toInstant());
}
传递Date 并返回一个。