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


Java DateFormat getInstance()用法及代碼示例

DateFormat 類的 getInstance() 方法將返回具有默認語言環境的默認格式樣式的日期和時間格式器。

用法:

public static final DateFormat getInstance()

參數:此方法不需要任何參數。

返回值:此方法將以特定格式返回日期格式。



範例1:

Java


// Java program to illustrate
// GetInstance() method
  
// importing the required packages
import java.text.DateFormat;
import java.util.Date;
  
class Testclass {
    public static void main(String[] args)
    {
  
        // initializing the Date
        Date d = new Date();
  
        // initializing the DateFormat using getInstance()
        DateFormat df = DateFormat.getInstance();
  
        // printing the DateFormat return value as object
        System.out.println("DateFormat Object:" + df);
  
        // formatting the current date into a string
        String str = df.format(d);
  
        // printing the current date
        System.out.println("Current date:" + str);
    }
}
輸出
DateFormat Object:java.text.SimpleDateFormat@c88bcc54
Current date:12/15/21, 8:23 AM

我們還可以使用 SimpleDateFormat 類以所需的格式顯示日期。

下麵是顯示使用 SimpleDateFormat 的示例

範例2:

Java


// Java program to illustrate
// GetInstance() method
  
// importing the required packages
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
  
class Testclass {
    public static void main(String[] args)
    {
        // initializing the Date
        Date d = new Date();
  
        // initializing the DateFormat using getInstance()
        DateFormat df = DateFormat.getInstance();
  
        // printing the DateFormat return value as object
        System.out.println("DateFormat Object:" + df);
  
        // formatting the current date into a string
        String str = df.format(d);
  
        // printing the current date
        System.out.println("Current date:" + str);
  
        // initializing the SimpleDateFormat
        SimpleDateFormat sdf
            = new SimpleDateFormat("MM-dd-yyyy");
  
        // formatting the SimpleDateFormatr into a string
        String st = sdf.format(d);
  
        // printing the formatted value
        System.out.println("Formatted Date:" + st);
    }
}
輸出
DateFormat Object:java.text.SimpleDateFormat@c88bcc54
Current date:12/15/21, 8:26 AM
Formatted Date:12-15-2021



相關用法


注:本文由純淨天空篩選整理自akashdeepkatari大神的英文原創作品 Java DateFormat getInstance() Method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。