1.Date轉(zhuǎn)String
1.1Date->String
//date->String
Date date = new Date();
String format = dateFormat.format(date);
System.out.println("format = " + format);
1.2String->Date
//yyyy-MM-dd HH:mm:ss
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = "2023-04-03";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//1.string->date
Date parse = dateFormat.parse(time);
System.out.println("parse = " + parse);
2.Date轉(zhuǎn)TimeStamp
2.1Date->TimeStamp
//Date->TimeStamp
Date date = new Date();
long time = date.getTime();
Timestamp createTime = new Timestamp(time);
System.out.println("createTime = " + createTime);
2.2TimeStamp->Date
//TimeStamp->Date
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date timestampToDate = new Date(timestamp.getTime());
System.out.println("timestampToDate = " + timestampToDate);
3.Date轉(zhuǎn)DateTime
DateTime使用依賴
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.1</version>
</dependency>
3.1Date->DateTime
方法1:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-606451.html
//method1
Date date = new Date();
DateTime dateTime1 = new DateTime(date);
方法2:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-606451.html
//method2
Date date = new Date();
String dateTimeString = new DateTime(date).toString("yyyy-MM-dd");
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime time = dateTimeFormatter.parseDateTime(dateTimeString);
System.out.println("Date->DateTime: " + time);
3.2DateTime->Date
//DateTime->Date
DateTime dateTime = new DateTime();
Date dateToDateTime = dateTime.toDate();
System.out.println("DateTime->Date" + dateToDateTime);
4.String轉(zhuǎn)DateTime
//String->DateTime
String dateTimeString = "2023-04-08";
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime time = dateTimeFormatter.parseDateTime(dateTimeString);
System.out.println("String->DateTime: " + time);
//DateTime->String
DateTime dt=new DateTime();
String format="YYYY-MM-dd HH-mm-ss";
String str= dt.toString(format);
System.out.println("DateTime->String = " + str);
5.String與TimeStamp互轉(zhuǎn)
String timeStr = "2023-04-06 10:30:40";
//String -> Timestamp
Timestamp time = Timestamp.valueOf(timeStr);
//Timestamp -> String
String strn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
System.out.println("Timestamp time = " + time);
System.out.println("strn = " + strn);
到了這里,關(guān)于java中日期轉(zhuǎn)換Date、DateTime、TimeStamp、String之間相互轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!