Java中Date, Calendar, SimpleDateFormat的相互转换

时间:2023-03-08 15:57:13
 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; public class MyUseSimpleDateFormat {
public static void main(String[] args) {
/**
* Date类通过getTime()返回long
* 通过void setTime(long time)设置时间
*/
Date date = new Date();
long time = date.getTime();
date.setTime(time);
/**
* SimpleDateFormat通过format()格式化为字符串
* 通过parse(String str)转为Date
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
try {
Date newDate = sdf.parse("1998-11-22 12:22:153");
System.out.println(newDate);
} catch (ParseException e) {}
/**
* Calendar通过getTime()方法转为Date
* Date通过setTime设置Calendar
*/
Calendar cal = Calendar.getInstance();
Date dt = cal.getTime();
System.out.println(dt);
cal.setTime(dt);
}
}