java中Date与String的相互转换

java中通过SimpleDateFormat可以实现Date与String的相互转换。

1.String转Date

例1:年月日 时分秒

String str1 = "2021-09-24 12:13:14";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate1 = null;
try {
    myDate1 = sdf1.parse(str1);
}catch (Exception e){
    e.printStackTrace();
}
System.out.println("myDate1: "+myDate1);

myDate1: Fri Sep 24 12:13:14 CST 2021

例2:年月日 时分

String str2 = "2021-09-24 12:13";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date myDate2 = null;
try {
    myDate2 = sdf2.parse(str2);
}catch (Exception e){
    e.printStackTrace();
}
System.out.println("myDate2: "+myDate2);

myDate2: Fri Sep 24 12:13:00 CST 2021

2.Date转String

Date myDate = new Date();
System.out.println("myDate:" + myDate + "\n");

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
String strDate1 = sdf1.format(myDate);
System.out.println("strDate1:" + strDate1);

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String strDate2 = sdf2.format(myDate);
System.out.println("strDate2:" + strDate2);

SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate3 = sdf3.format(myDate);
System.out.println("strDate3:" + strDate3);

SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String strDate4 = sdf4.format(myDate);
System.out.println("strDate4:" + strDate4);

myDate:Fri Sep 24 21:45:32 CST 2021

strDate1:2021-09-24
strDate2:2021-09-24 21:45
strDate3:2021-09-24 21:45:32
strDate4:2021年09月24日 21时45分32秒



参考

  • https://www.cnblogs.com/huangminwen/p/5994846.html

你可能感兴趣的:(java,java,Date,时间形式转换)