如何在 Java 中從年、月和日獲取日期?


使用 of() 方法

 java.time.LocalDate 類的 of() 方法接受年、月和日作為引數,建立並返回一個 LocalDate 物件。

示例

線上演示

import java.time.LocalDate;
public class Test {
   public static void main(String[] args) {
      LocalDate date = LocalDate.of(2014, 9, 11);
      System.out.println("Date Value: "+date);
   }
}

輸出

Date Value: 2014-09-11

使用 GregorianCalendar 類

java.util.GregorianCalendar 類的一個構造器接受年、月和日作為值,並建立一個表示它的 Calendar 物件。

示例

import java.util.*;
class Test {  
   public static void main(String args[]){
      //Creating a calendar object
      Calendar cal = new GregorianCalendar(2020, 07, 18);
      int day = cal.get(Calendar.DAY_OF_MONTH);
      int month = cal.get(Calendar.MONTH);
      int year = cal.get(Calendar.YEAR);
      System.out.println("Day: " + day);
      System.out.println("Month: " + month);
      System.out.println("Year: " + year);
    }
}

輸出

Day: 18
Month: 7
Year: 2020

使用 SimpleDateFormat 物件

此類的構造器之一接受一個表示所需日期格式的字串值,並建立一個**SimpleDateFormat 物件。**要將字串解析/轉換為日期物件?-

  • 透過傳遞所需格式字串來例項化此類。
  • 使用 parse() 方法解析日期字串。

示例

線上演示

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
   public static void main(String args[]) throws ParseException {  
      String date_string = "2007-25-06";
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");      
      //Parsing the given String to Date object
      Date date = formatter.parse(date_string);      
      System.out.println("Date value: "+date);
   }
}

輸出

Date value: Mon Jun 25 00:00:00 IST 2007

更新於:2021-02-05

6K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.