likes
comments
collection
share

Java8 LocalDateTime获取当前周是本年第几周weekOfYear,用WeekFields

作者站长头像
站长
· 阅读数 48

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);
		
	}

}

Java8 LocalDateTime获取当前周是本年第几周weekOfYear,用WeekFields

例子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));
		
		
	}

}

Java8 LocalDateTime获取当前周是本年第几周weekOfYear,用WeekFields

转载自:https://juejin.cn/post/7247428110164836389
评论
请登录