首页 > 基础资料 博客日记
java中日期转换Date、DateTime、TimeStamp、String之间相互转换
2023-07-24 16:16:31基础资料围观237次
文章java中日期转换Date、DateTime、TimeStamp、String之间相互转换分享给大家,欢迎收藏Java资料网,专注分享技术知识
1.Date转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转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转DateTime
DateTime使用依赖
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.1</version>
</dependency>
3.1Date->DateTime
方法1:
//method1
Date date = new Date();
DateTime dateTime1 = new DateTime(date);
方法2:
//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转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互转
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);
文章来源:https://blog.csdn.net/m0_64887997/article/details/130031520
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: