当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。