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


Java LocalDateTime minusWeeks()用法及代碼示例


LocalDateTime類minusWeeks()方法

  • minusWeeks() 方法可在java.time包。
  • minusWeeks() 方法用於從此日期時間對象中減去給定的周數並返回 LocalDateTime。
  • minusWeeks() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • minusWeeks() 方法可能會在執行減法時拋出異常。
    DateTimeException – 當計算的結果值超過限製時可能會拋出此異常。

用法:

    public LocalDateTime minusWeeks(long weeks_val);

參數:

  • long weeks_val– 表示要從此 LocalDateTime 中減去的周數。

返回值:

這個方法的返回類型是LocalDateTime,它返回保存從該 LocalDateTime 減去給定周的值的 LocalDateTime。

例:

// Java program to demonstrate the example 
// of minusWeeks(long weeks_val) method 
// of LocalDateTime

import java.time.*;

public class MinusWeeksOfLocalDateTime {
    public static void main(String args[]) {
        long weeks = 1;
        // Instantiates two LocalDateTime
        LocalDateTime da_ti1 = LocalDateTime.parse("2005-10-05T10:10:10.00");
        LocalDateTime da_ti2 = LocalDateTime.now();

        // Display da_ti1, da_ti2 and
        // weeks
        System.out.println("LocalDateTime da_ti1 and da_ti2:");
        System.out.println("da_ti1:" + da_ti1);
        System.out.println("da_ti2:" + da_ti2);
        System.out.println("weeks to subtract:" + weeks);

        System.out.println();

        // Here, this method subtracts the given
        // weeks from this date-time object 
        // i.e. here we are subracting 1 week from 
        // this object da_ti1
        LocalDateTime minus_weeks = da_ti1.minusWeeks(weeks);

        // Display minus_weeks
        System.out.print("da_ti1.minusWeeks(weeks):");
        System.out.println(minus_weeks);

        // Here, this method subtracts the given
        // weeks from this date-time object i.e.
        // here we are subracting 1 week from 
        // this object da_ti2
        minus_weeks = da_ti2.minusWeeks(weeks);

        // Display minus_weeks
        System.out.print("da_ti2.minusWeeks(weeks):");
        System.out.println(minus_weeks);
    }
}

輸出

LocalDateTime da_ti1 and da_ti2:
da_ti1:2005-10-05T10:10:10
da_ti2:2020-06-08T03:03:18.495162
weeks to subtract:1

da_ti1.minusWeeks(weeks):2005-09-28T10:10:10
da_ti2.minusWeeks(weeks):2020-06-01T03:03:18.495162


相關用法


注:本文由純淨天空篩選整理自 Java LocalDateTime Class | minusWeeks() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。