📜  Java中的 SimpleDateFormat format() 方法及示例

📅  最后修改于: 2022-05-13 01:54:38.656000             🧑  作者: Mango

Java中的 SimpleDateFormat format() 方法及示例

SimpleDateFormat 类format()方法用于将给定日期格式化为日期/时间字符串。基本上,该方法用于将此日期和时间转换为特定格式,例如 mm/dd/yyyy。
句法:

public final String format(Date date)

参数:该方法接受一个Date对象类型的参数date ,指的是要产生字符串输出的日期。
返回值:该方法以mm/dd/yyyy的字符串格式返回日期或时间。
下面的程序说明了 SimpleDateFormat 的 format() 方法的工作:
示例 1:

Java
// Java code to illustrate format() method
 
import java.text.*;
import java.util.Calendar;
 
public class SimpleDateFormat_Demo {
    public static void main(String[] args)
        throws InterruptedException
    {
        SimpleDateFormat SDFormat
            = new SimpleDateFormat("MM/dd/yyyy");
 
        // Initializing the calendar Object
        Calendar cal = Calendar.getInstance();
 
        // Displaying the actual date
        System.out.println("The original Date: "
                           + cal.getTime());
 
        // Using format() method for conversion
        String curr_date
            = SDFormat.format(cal.getTime());
        System.out.println("Formatted Date: "
                           + curr_date);
    }
}


Java
// Java code to illustrate format() 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();
 
        // Displaying the actual date
        System.out.println("The original Date: "
                           + cal.getTime());
 
        // Using format() method for conversion
        String curr_date = SDFormat.format(cal.getTime());
        System.out.println("Formatted Date: "
                           + curr_date);
    }
}


输出:
The original Date: Tue Jan 29 12:23:40 UTC 2019
Formatted Date: 01/29/2019

示例 2:

Java

// Java code to illustrate format() 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();
 
        // Displaying the actual date
        System.out.println("The original Date: "
                           + cal.getTime());
 
        // Using format() method for conversion
        String curr_date = SDFormat.format(cal.getTime());
        System.out.println("Formatted Date: "
                           + curr_date);
    }
}
输出:
The original Date: Tue Jan 29 12:29:32 UTC 2019
Formatted Date: 1/29/19 12:29 PM