Java DateFormat getDateTimeInstance()方法及示例
java.text包中的DateFormat类是一个抽象的类,用于格式化和解析任何地区的日期。它允许我们将日期格式化为文本并将文本解析为日期。DateFormat类提供了许多功能来获取、格式化、解析默认的日期/时间。
注意: DateFormat类扩展了Format类,这意味着它是Format类的一个子类。由于DateFormat类是一个抽象类,因此,它可以用于日期/时间格式化子类,以独立于语言的方式格式化和解析日期或时间。
包-视图
java.text Package DateFormat Class getDateTimeInstance() Method
Java中 DateFormat类 的 getDateTimeInstance() 方法被用来获取日期/时间格式化。这个日期/时间格式化器带有默认地区的默认格式化风格。
语法
public static final DateFormat getDateTimeInstance()
返回类型: 该方法返回一个特定格式的日期/时间格式器。
例子1 :
// Java Program to Illustrate the// getDateTimeInstance() 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 by // creating object of DateFormat class DateFormat DFormat = DateFormat.getDateTimeInstance(); System.out.println("Object: " + DFormat); // Formatting the string using format() method String str = DFormat.format(new Date()); // Printing the formatted string time System.out.println(str); }}输出
Object: java.text.SimpleDateFormat@f95cf381Jan 11, 2022, 6:25:40 AM
例2 :
// Java Program to Illustrate the// getDateTimeInstance() 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 SimpleDateFormat SDFormat = new SimpleDateFormat("MM/dd/yyyy"); // Displaying the formats Date date = new Date(); String str_Date1 = SDFormat.format(date); // Displaying the unformatted date System.out.println("The Original: " + (str_Date1)); // Initializing the Time formatter DateFormat DFormat = DateFormat.getDateTimeInstance(); System.out.println("Object: " + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Displaying the string time on console System.out.println(str); }}输出
The Original: 01/11/2022Object: java.text.SimpleDateFormat@f95cf381Jan 11, 2022, 6:30:09 AM
