一年中的第一周的时间

问题描述 投票:0回答:1

我需要从年的第几周获得Instant时间。现在,我正在使用旧的Calendar API来计算时间:

int week = 1; // week of year
final Calendar cal = new GregorianCalendar();
cal.set(0, 1, 0, 0, 0, 0); // reset calendar
cal.set(Calendar.YEAR, Year.now().getValue());
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
final Instant start = cal.getTime().toInstant();
final Instant end = start.plus(Period.ofWeeks(1));

是否可以使用新的Java时间API(Instant程序包)从一年中的某个星期获得java.time

java time java-time
1个回答
0
投票

您可以使用以下方法调整星期:

LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 0, 0);
System.out.println(localDateTime); //2020-01-01T00:00
localDateTime = localDateTime.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 2);
System.out.println(localDateTime); //2020-01-08T00:00
localDateTime = localDateTime.plusWeeks(10);
System.out.println(localDateTime); //2020-03-18T00:00

并将其解析为Instant取决于您所使用的API中的类:

LocalDateTime.now().toInstant(ZoneOffset.of("+04:00"));
ZonedDateTime.now().toInstant();

LocalDateTime没有区域,因此您必须提供ZoneOffset才能将其解析为Instant。


0
投票

LocalDate.now().with(temporal -> temporal.with(ChronoField.MONTH_OF_YEAR, 1l) )

© www.soinside.com 2019 - 2024. All rights reserved.