当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java TemporalAdjusters firstInMonth()用法及代码示例


TemporalAdjusters类的firstInMonth(DayOfWeek)方法用于返回TemporalAdjuster对象,该对象可用于获取新的Date对象,该对象是同月匹配的DayOfWeek作为从任何Date对象作为参数传递的同月的第一天此TempotralAdjuster应用于其上。

用法:

public static TemporalAdjuster
       firstInMonth(DayOfWeek dayOfWeek)

参数:此方法接受dayOfWeek,可用于获取新的Date对象,该对象是具有相同匹配的DayOfWeek的同一月份的第一个日期。



返回值:此方法返回月份中的第一个调节器,而不是null。

以下示例程序旨在说明TemporalAdjusters.firstInMonth()方法:
程序1:

// Java program to demonstrate 
// TemporalAdjusters.firstInMonth() 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // get TemporalAdjuster with 
        // the first in month adjuster 
        TemporalAdjuster temporalAdjuster 
            = TemporalAdjusters.firstInMonth( 
                DayOfWeek.SUNDAY); 
  
        // using adjuster for local date time 
        LocalDate localDate 
            = LocalDate.of(2023, 10, 11); 
        LocalDate firstInMonth 
            = localDate.with(temporalAdjuster); 
  
        // print 
        System.out.println( 
            "First date in month having"
            + " sunday for localdate "
            + localDate + " is:"
            + firstInMonth); 
    } 
}
输出:
First date in month having sunday for localdate 2023-10-11 is:2023-10-01

程序2:

// Java program to demonstrate 
// TemporalAdjusters.firstInMonth() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // get TemporalAdjuster with 
        // the first in month adjuster 
        TemporalAdjuster temporalAdjuster 
            = TemporalAdjusters.firstInMonth( 
                DayOfWeek.TUESDAY); 
  
        // using adjuster for local date-time 
        LocalDate localDate 
            = LocalDate.of(2023, 10, 11); 
        LocalDate firstInMonth 
            = localDate.with(temporalAdjuster); 
  
        // print 
        System.out.println( 
            "First date in a month having"
            + " TUESDAY for localdate "
            + localDate + " is:"
            + firstInMonth); 
    } 
}
输出:
First date in a month having TUESDAY for localdate 2023-10-11 is:2023-10-03

参考文献:https://docs.oracle.com/javase/10/docs/api/java/time/temporal/TemporalAdjusters.html#firstInMonth(java.time.DayOfWeek)




相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 TemporalAdjusters firstInMonth() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。