Java 中的 SimpleDateFormat 是什麼?
java.text.SimpleDateFormat 類用於將字串格式化為日期,或將日期格式化為字串。
解析日期字串
此類的其中一個建構函式接受一個表示所需日期格式的字串值,並建立 SimpleDateFormat 物件。要將字串解析/轉換為日期物件
- 透過傳遞所需格式字串例項化此類。
- 使用 parse() 方法解析日期字串。
示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
public static void main(String args[]) throws ParseException {
String date_string = "2007-25-06";
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
//Parsing the given String to Date object
Date date = formatter.parse(date_string);
System.out.println("Date value: "+date);
}
}輸出
Date value: Mon Jun 25 00:00:00 IST 2007
檢索模式字串
此類的 toPattern() 方法返回表示當前物件格式的模式字串。
示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Demo {
public static void main(String args[]) throws ParseException {
SimpleDateFormat obj = new SimpleDateFormat();
String pattern = obj.toPattern();
System.out.println(pattern);
}
}輸出
M/d/yy h:mm a
從文字中解析日期
此類的 parse() 方法接受與日期字串一起的 ParsePosition,並從文字中解析日期。
示例
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
public static void main(String args[]) throws ParseException {
String text = "Marriage date of Samrat is 2007-25-06";
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
//Parsing date from the given text
ParsePosition pos = new ParsePosition(27);
Date date = formatter.parse(text, pos);
System.out.println("Date value: "+date);
}
}輸出
Date value: Mon Jun 25 00:00:00 IST 2007
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP