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


Java SimpleDateFormat applyPattern()用法及代碼示例


SimpleDateFormat類的applyPattern()方法用於將給定的已定義模式設置為“日期格式”。它僅將特定日期和時間轉換為用戶定義的特定格式,例如dd /MM /yyyy HH:mm Z或MM /dd /yyyy HH:mmZ。

用法:

public void applyPattern(String pattern)

參數:該方法采用一種String類型的參數模式,表示此日期格式的新日期和時間模式。


返回值:該方法返回void類型。

以下示例程序旨在說明SimpleDateFormat的applyPattern()方法的用法:

示例1:

// Java code to illustrate 
// applyPattern() method 
  
import java.text.*; 
import java.util.Calendar; 
  
public class SimpleDateFormat_Demo { 
  
    public static void main(String[] args) 
        throws InterruptedException 
    { 
        SimpleDateFormat SDFormat 
            = new SimpleDateFormat(); 
  
        // Initializing the calender Object 
        Calendar cal = Calendar.getInstance(); 
  
        // Using the below pattern 
        String new_pat = "dd/ MM/ yyyy HH:mm Z"; 
  
        // Use of applyPattern() method 
        SDFormat.applyPattern(new_pat); 
  
        // Displaying Current date and time 
        String curr_date 
            = SDFormat.format(cal.getTime()); 
  
        System.out.println("The Current Date: "
                           + curr_date); 
  
        // Displaying the pattern 
        System.out.println("Applied Pattern: "
                           + SDFormat.toPattern()); 
    } 
}
輸出:
The Current Date: 29/ 01/ 2019 07:22 +0000
Applied Pattern: dd/ MM/ yyyy HH:mm Z

示例2:

// Java code to illustrate 
// applyPattern() method 
  
import java.text.*; 
import java.util.Calendar; 
  
public class SimpleDateFormat_Demo { 
  
    public static void main(String[] args) 
        throws InterruptedException 
    { 
        SimpleDateFormat SDFormat 
            = new SimpleDateFormat(); 
  
        // Initializing the calender Object 
        Calendar cal = Calendar.getInstance(); 
  
        // Using the below pattern 
        String new_pat = "MM/ dd/ yyyy HH:mm Z"; 
  
        // Use of applyPattern() method 
        SDFormat.applyPattern(new_pat); 
  
        // Displaying Current date and time 
        String curr_date 
            = SDFormat.format(cal.getTime()); 
        System.out.println("The Current Date: "
                           + curr_date); 
  
        // Displaying the pattern 
        System.out.println("Applied Pattern: "
                           + SDFormat.toPattern()); 
    } 
}
輸出:
The Current Date: 01/ 29/ 2019 07:22 +0000
Applied Pattern: MM/ dd/ yyyy HH:mm Z


相關用法


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