在Java中,我们可以使用parse()方
法将String转换为Date。
Java中String转Date示例
示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
//零五网 www.02405.com
public class StringToDateExample1 {
public static void main(String[] args)throws Exception {
String sDate1="22/11/2022";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
System.out.println(sDate1+"\t"+date1);
}
}
输出:
22/11/2022 Tue Nov 22 00:00:00 UTC 2022
Java中不同格式的String转换为Date示例
示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
//零五网 www.02405.com
public class StringToDateExample2 {
public static void main(String[] args)throws Exception {
String sDate1="22/11/2022";
String sDate2 = "22-11-2022";
String sDate3 = "11 22, 2022";
String sDate4 = "Tue, Nov 22 2022";
String sDate5 = "Tue, Nov 22 2022 23:37:50";
String sDate6 = "22-11-2022 23:37:50";
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatter2=new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat formatter3=new SimpleDateFormat("MM dd, yyyy");
SimpleDateFormat formatter4=new SimpleDateFormat("E, MMM dd yyyy");
SimpleDateFormat formatter5=new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");
SimpleDateFormat formatter6=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date1=formatter1.parse(sDate1);
Date date2=formatter2.parse(sDate2);
Date date3=formatter3.parse(sDate3);
Date date4=formatter4.parse(sDate4);
Date date5=formatter5.parse(sDate5);
Date date6=formatter6.parse(sDate6);
System.out.println(sDate1+"\t"+date1);
System.out.println(sDate2+"\t"+date2);
System.out.println(sDate3+"\t"+date3);
System.out.println(sDate4+"\t"+date4);
System.out.println(sDate5+"\t"+date5);
System.out.println(sDate6+"\t"+date6);
}
}
输出:
22/11/2022 Tue Nov 22 00:00:00 UTC 2022 22-11-2022 Tue Nov 22 00:00:00 UTC 2022 11 22, 2022 Tue Nov 22 00:00:00 UTC 2022 Tue, Nov 22 2022 Tue Nov 22 00:00:00 UTC 2022 Tue, Nov 22 2022 23:37:50 Tue Nov 22 23:37:50 UTC 2022 22-11-2022 23:37:50 Tue Nov 22 23:37:50 UTC 2022