如何在 Java 中將日期格式化為字串?
java.text 包提供的一個名為 SimpleDateFormat 的類,用於按照所需的方式(本地)格式化和解析日期。
使用此類的這些方法,可以將字串解析為日期,或將日期格式化為字串。
將日期格式化為字串
可以使用 SimpleDateFormat 類的 parse() 方法將給定的字串格式化為日期物件。此方法需要傳入字串格式的日期。將字串格式化為日期物件 -
透過將所需日期模式(字串格式)作為引數傳遞給其建構函式,例項化 SimpleDateFormat 類。
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");透過將所需日期物件作為引數傳遞給 format() 方法,格式化/轉換日期物件為字串。
//Formatting the obtained date String formattedDate = formatter.format(date);
示例
以下 Java 程式將當前日期格式化為字串並列印。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
public class DateToString {
public static void main(String args[]) throws ParseException {
//Retrieving the current date
LocalDate localDate = LocalDate.now();
//Converting LocalDate object to Date
Date date = java.sql.Date.valueOf(localDate);
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
//Formatting the obtained date
String formattedDate = formatter.format(date);
System.out.println("Formatted date: "+formattedDate);
}
}輸出
Formatted date: 31-05-2019
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP