Java DateFormat getDateInstance()方法及示例
java.text包中的DateFormat类是一个抽象的类,用于格式化和解析任何地区的日期。它允许我们将日期格式化为文本并将文本解析为日期。DateFormat类提供了许多功能来获取、格式化、解析默认的日期/时间。
注意: DateFormat类扩展了Format类,这意味着它是Format类的一个子类。由于DateFormat类是一个抽象类,因此,它可以用于日期/时间格式化子类,以独立于语言的方式格式化和解析日期或时间。
包-视图 。
java.text **Package** DateFormat **Class** getDateInstance() **Method**
Java中 DateFormat类 的 getDateInstance() 方法被用来获取日期格式化。这个日期格式化器带有默认地区的默认格式化风格。
语法
public static final DateFormat getDateInstance()
返回类型: 返回一个特定格式的日期。
例子1 :
// Java Program to Illustrate getDateInstance() Method// of DateFormat Class // Importing required classesimport java.text.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) { // Initializing the first formatter // using getDateInstance() method DateFormat DFormat = DateFormat.getDateInstance(); System.out.println("Object: " + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Printing the string date on console System.out.println(str); }}输出
Object: java.text.SimpleDateFormat@ce9bf0a5Mar 27, 2019
例2 :
// Java Program to Illustrate getDateInstance() Method// of DateFormat Class // Importing required classesimport java.text.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws InterruptedException { // Initializing SimpleDateFormat by // creating object of SimpleDateFormat class SimpleDateFormat SDFormat = new SimpleDateFormat("MM/dd/yyyy"); // Printing the formats Date date = new Date(); String str_Date1 = SDFormat.format(date); // Displaying the original date System.out.println("The Original: " + (str_Date1)); // Initializing the Date formatter DateFormat DFormat = DateFormat.getDateInstance(); System.out.println("Object: " + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Printing the string date on console System.out.println(str); }}输出
The Original: 01/11/2022Object: java.text.SimpleDateFormat@ad508834Jan 11, 2022
