Date日期类、SimpleDateFormat日期格式类

一、Date日期类
1.Date表示特定的时间,精确到毫秒。
2.构造方法:
    (1)public Date():无参的构造方法,构造一个Date日期对象,并初始化对象为当前系统时间。
    (2)public Date(long date):表示自从基准时间1970年1月1日0时0分0秒以来的指定毫秒数。
    (3)常用方法:
        ①public long getTime():得到1970年1月1日0时0分0秒到当前日期对象的毫秒数。
        ②public void setTime():设置日期时间
        ③public boolean before(Date when):测试此日期是否在指定日期之前
        ④public boolean after(Date when):测试此日期是否在指定日之后
        ⑤public int compareTo(Date afterDate):如果此Date和传进来的Date一样就返回0,在它之前就返回小于0得数,在它之后就返回大于0的数
        ⑥public String toString():将日期格式转换为字符串格式输出
二、SimpleDateFormat日期格式类
1.DateFormat是日期/时间格式化抽象类,它以与语言无关的方式格式化并分析日期或时间
2.日期/时间格式化子类(如:SimpleDateFormat)允许进行格式化,也就是日期-->文本、文本-->日期的转换。
3.构造方法:
    (1)public SimpleDateFormat()
    (2)public SimpleDateFormat(String pattern)
4.常用方法:
    (1)public final String format(Date date)
    (2)public Date parse(String source)
    
public class Demo {
public static void main(String[] args) throws ParseException {
Date date = new Date();
System.out.println(date);// Mon Apr 16 21:12:43 CST 2018
System.out.println(date.getTime());// 1523884406155
date.setTime(1523884406155L);
System.out.println(date);// Mon Apr 16 21:13:26 CST 2018
//-------------我是分割线----------------//
DateFormat df1 = null;
DateFormat df2 = null;
DateFormat df3 = null;
DateFormat df4 = null;
df1 = DateFormat.getDateInstance();// 默认格式的日期格式化对象
df2 = DateFormat.getDateTimeInstance();// 产生DateFormat子类对象
System.out.println("Date:" + df1.format(date));// Date:2018-4-16
System.out.println("DateTime:" + df2.format(date));// DateTime:2018-4-16 21:13:26
//---------我是分割线--------------//
df3 = DateFormat.getDateInstance(DateFormat.FULL, new Locale("zh", "CN"));
System.out.println("Date:" + df3.format(date));// Date:2018年4月16日 星期一(还有LONG,SHORT类型)
df4 = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, new Locale("zh" ,"cn"));
System.out.println("DateTime:" + df4.format(date));// DateTime:2018年4月16日 星期一 下午09时13分26秒 CST
//---------我是分割线--------------//
String strDate = "2010-10-19 10:11:30.345";
Date d = null;
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH-mm-ss.SSS");
d = sdf1.parse(strDate);// 把日期字符串中的日期部分抽取出来生成Date对象
System.out.println(d);// Tue Oct 19 10:11:30 CST 2010
String format = sdf2.format(d);// 把日期按指定的模板格式格式化输出为字符串
System.out.println(format);// 2010年10月19日 10-11-30.345
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42051619/article/details/80958169