------- android培训、java培训、期待与您交流! ----------
Date类
1 Date类概述
Date类对象表示日期和时间,即年、月、日、时、分、秒。
2 Date类的构造器
l Date()
l Date(long) – new Date(0)表示(1970年1月1日,00:00:00)。但因为中国是东八区,所以是表示(1970年1月1日,08:00:00)。其中参数可以是负数,表示“基准时间”之前。
3 Date类的方法
l boolean after(Date when):当前时间是否在参数时间之后。d1.after(d2)
l boolean before(Date when):当前时间是否在参数时间之前
l int compareTo(Date date):当this>data返回正数,this<date返回负数,否则返回0。d1.compareTo(d2)
l boolean equals(Date date):比较当前时间和参数时间是否相等。
l long getTime():获取当前时间毫秒值
l void setTime(long time):设置当前时间毫秒值
l String toString()
日期格式化器
1 Date概述
它是一个抽象类,在java.text包下。
我们中需要学习一个方法,format(Date)
2 获取DateFormat实例的方法
我们知道它有一个子类:SimpleDateFormat
3 获取DateFormat实例的其它方法
l 获取只对日期格式化的DateFormat实例;
l 获取只对时间格式化的DateFormat实例;
l 获取对日期和时间格式化的DateFormat实例;
4 获取DateFormat实例(完全FULL、长LONG、中SHORT、短MEDIUM)
l 获取完整格式的DateFormat实例;
l 获取长格式的DateFormat实例;
l 获取中格式的DateFormat实例;
l 获取短格式的DateFormat实例;
SimpleDateFormat
1 SimpleDateFormat类概述
DateFormat类的子类!
其实DateFormat类的所有获取DateFormat实例的方法,返回的都是SimpleDateFormat类的对象。
2 SimpleDateFormat构造器(指定格式)
SimpleDateFormat(String pattern):指定模式字符串来构造对象。
其中参数表示一个模式字符串,它表示如何格式化Date对象。这其中需要使用模式字符!
y – 表示年
M – 表示月
d -- 表示日期
H – 表示小时(0~23)
m – 给分钟
s – 表示秒钟
例如:new SimpleDateFormat(“yyyy年MM月dd日”);
如果使用了错误的模式字符,那么构造器会抛出异常。
3 把String转换成Date对象
把String转换成Date需要使用SimpleDateFormat类的Dateparse(String)方法
例如:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2012-12-28 18:12:34");
System.out.println(date);
注意,parse()方法声明了ParseException。当parse()方法的参数不能匹配SimpleDataFormat的模式字符串时,那么就抛出ParseException。
其它格式化
Date d = new Date();
String str = String.format("%tF %<tR", d);
System.out.println(str);
str = String.format("%tF %<tT", d);
System.out.println(str);