版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32314965/article/details/87655174
Date表示时刻,内部主要是一个long型的值,如下
private transient long fastTime;//fastTime表示的是距离纪元1900年1月1日0时0分0秒的毫秒数
Date有两个构造方法:
public Date() {
this(System.currentTimeMillis());
}//默认构造方法,根据System.currentTimeMillis()返回的毫秒数进行初始化
public Date(long date) {
fastTime = date;
}//根据传入的毫秒数进行初始化
Date中大部分方法都已经过时,没有过时的主要方法:
public long getTime() {
return getTimeImpl();
}//返回毫秒数,可以用来对日期进行运算
private final long getTimeImpl() {
if (cdate != null && !cdate.isNormalized()) {
normalize();
}
return fastTime;
}
public boolean before(Date when)//判断是否在给定日期之前
public boolean after(Date when)//判断是否在给定日期之后
public int compareTo(Date anotherDate)//与给定日期作比较
SimpleDateFormat是DateFormat的子类,他可以接受一个自定义的pattern作为参数,这个参数规定Date的字符串形式。
public Date parse(String source) throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}//parse方法将字符串转换成指定格式的Date
public final String format(Date date)
{
return format(date, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}//format方法将指定时间转换为字符串
利用这两个方法可以很方便的将时间在字符串和Date之间相互转换:
public class Main {
public static void main(String[] args) throws IOException, ParseException {
String str = "2016-08-15 14:15:20";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(str);
System.out.println(date);//字符串转换为时间
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
System.out.println(sdf2.format(date));//时间转换为指定格式的字符串
}
}
输出结果:
Mon Aug 15 14:15:20 CST 2016
2016年08月15日 14:15:20