當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。