如何使用 SimpleDateFormat 在 Java 中格式化日期字串?
此類的其中一個建構函式接受表示所需日期格式的字串值並建立SimpleDateFormat 類。 要將字串解析/轉換為 Date 物件,請 −
- 透過傳遞所需的格式字串來例項化此類。
- 使用 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
廣告