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

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

		
	}

}

在这里插入图片描述

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYU5RZZx' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片