Java8 LocalDateTime获取当前周是本年第几周weekOfYear, 可用WeekFields
LocalDateTime 没有直接获得 weekOfYear 的方法
LocalDateTime 有一个 get(TemporalField field)
方法, 返回 int
public int get(TemporalField field) {
if (field instanceof ChronoField chronoField) {
return (chronoField.isTimeBased() ? time.get(field) : date.get(field));
}
return ChronoLocalDateTime.super.get(field);
}
TemporalField
可通过 WeekFields
的实例的方法获得 其中就有 weekOfYear()
WeekFields
有两个静态的默认的 WeekFields
实例
WeekFields.ISO
每周由星期一开始WeekFields.SUNDAY_START
每周由星期日开始
WeekFields
的实例,获取TemporalField
的方法有
- public TemporalField
dayOfWeek()
- public TemporalField
weekOfMonth()
- public TemporalField
weekOfYear()
- public TemporalField
weekOfWeekBasedYear()
- public TemporalField
weekBasedYear()
其中 weekOfYear()
就是获取 获取当前周的TemporalField
例子1
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.Calendar;
public class LocalDateTime获取当前周是第几周2306222222 {
public static void main(String...arguments)throws Exception{
LocalDateTime localDateTime = LocalDateTime.now();
int 第几周ByLocalDateTime = localDateTime.get(WeekFields.ISO.weekOfYear());
System.out.println("第几周ByLocalDateTime="+第几周ByLocalDateTime);
Calendar calendar = Calendar.getInstance();
int 第几周ByCalendar = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("第几周ByCalendar="+第几周ByCalendar);
}
}
例子2
package tempTestTry;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.Calendar;
public class LocalDateTime获取当前周是第几周2306222303 {
public static void main(String...arguments)throws Exception{
System.out.println("LocalDateTime.now().get(WeekFields.ISO.weekOfYear())="+LocalDateTime.now().get(WeekFields.ISO.weekOfYear()));
System.out.println("LocalDateTime.now().get(WeekFields.SUNDAY_START.weekOfYear())="+LocalDateTime.now().get(WeekFields.SUNDAY_START.weekOfYear()));
System.out.println("Calendar.getInstance().get(Calendar.WEEK_OF_YEAR)="+Calendar.getInstance().get(Calendar.WEEK_OF_YEAR));
}
}