文章目录
Java 常见的日期转换(Timestamp、Calendar、Date、String)
日期类型:
- Timestamp: java.sql.Timestamp
- Calendar: java.util.Calendar
- Date: java.util.Date
- String: java.lang.String
1、Timestamp 转 Calendar
Timestamp timestamp = Timestamp.valueOf("2023-06-06 21:39:52");
Calendar calendar = Calendar.getInstance();
calendar.setTime(timestamp);
2、Timestamp 转 Date
Timestamp timestamp = Timestamp.valueOf("2023-06-06 21:39:52");
long time = timestamp.getTime();
Date date = new Date(time);
3、Timestamp 转 String
Timestamp timestamp = Timestamp.valueOf("2023-06-06 21:39:52");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(timestamp);
4、Calendar 转 Timestamp
Calendar calendar = Calendar.getInstance();
long time = calendar.getTimeInMillis();
Timestamp timestamp = new Timestamp(time);
5、Calendar 转 Date
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
6、Calendar 转 String
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(calendar.getTime());
7、Date 转 Calendar
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
8、Date 转 Timestamp
Date date = new Date();
long time = date.getTime();
Timestamp timestamp = new Timestamp(time);
9、Date 转 String
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat