Java SimpleDateFormat applyPattern()方法及示例
SimpleDateFormat类 的 applyPattern() 方法用于为日期格式设置一个给定的定义模式。它简单地将一个特定的日期和时间转换为用户定义的特定格式,例如,dd/ MM/ yyyy HH:mm Z或MM/ dd/ yyyy HH:mm Z。
语法:
public void applyPattern(String _pattern_ )
参数: 该方法接收一个字符串类型的参数 模式 ,并指该日期格式的新日期和时间模式。
返回值: 该方法返回无效类型。
以下程序说明了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 calendar 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 +0000Applied 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 calendar 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 +0000Applied Pattern: MM/ dd/ yyyy HH:mm Z
