Java的时间处理类十分强大,使用非常方便,特此总结。
Date =====>>DateFormat=====>> SimpleDateFormat
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTimeInMillis());
System.out.println(System.currentTimeMillis());
System.out.println(calendar.getTimeZone());//获取时区
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//获取月份中的日期
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));//获取一个星期中星期几,从星期日开始算
//Date构造方法
Date date =
new
Date();
//当前时间
Date date2 =
new
Date (2018,10,01);
//指定时间
//方法
//比较
date.after( date2);
date.before(date2);
//获取年月日时分秒
date. getYear();
//要加1900才能等于当前的年份
date. getMonth();
date. getDay();
date. getDate();
date.getTime();
//与Long time = System.currentTimeMillis()一样
//设置年月日
date. setYear(1990);
date. setMonth(12);
date. setHours(12);
===>>
计算机是这个毫秒值表示时间,人们可不愿意说" 我将在996,321,998,34见到你。"幸运的是,Java提供了一个转换Date对象到字符串的途径,表示成传统的形式。
//DateFormat
//构造方法
/*因为语言的差别,不是所有的人希望看到严格的相同格式的日期。
法国人更喜欢看到"25 decembre 2000," ,
但是美国人习惯看到"December 25,2000."
所以一个DateFormat的实例创建以后,这个对象包含了日期的显示格式的信息。
如果使用用户电脑区域设置缺省的格式,你可以象下面那样,创建DateFormat对象,使用getDateInstance()方法*/
DateFormat df = DateFormat.getInstance ();
//不同的格式
DateFormat df1 = DateFormat.getDateInstance(DateFormat.
SHORT
);
DateFormat df2 = DateFormat.getDateInstance(DateFormat.
MEDIUM
);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.
LONG
);
DateFormat df4 = DateFormat.getDateInstance(DateFormat.
FULL
);
//SimpleDateFormat,自定义显示格式
SimpleDateFormat sdf =
new
SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss"
);
SimpleDateFormat sdf1 =
new
SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss"
);
SimpleDateFormat sdf2 =
new
SimpleDateFormat(
"yyyy-MM-dd HH:mm"
);
SimpleDateFormat sdf3 =
new
SimpleDateFormat(
"yyyy-MM-dd HH:mm"
);
//simpleDateFormat的format及parse方法
parse(String text, ParsePosition pos)
parse(String text, ParsePosition pos)
解析字符串的文本,生成 Date。
format(Date date, StringBuffer toAppendTo, FieldPosition pos)
将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。
将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。
熟练使用parse和format方法,可将一种格式的时间字符串,转换成另一种,这在实际项目中经常用到。
举例:
String type =
"2014-11-20 19:01:59"
;
Date date4 =
null
;
try
{
date4 = sdf.parse(type);
}
catch
( ParseException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
System.
out
.println(sdf1.format(date4));
示意图:
//抽象类Calendar声明方法
Calendar的使用,Calendar是声明为抽象类的,打开源码可以看到getInstance()获取的是
GregorianCalendar()的对象
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTimeInMillis());
System.out.println(System.currentTimeMillis());
System.out.println(calendar.getTimeZone());//获取时区
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//获取月份中的日期
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));//获取一个星期中星期几,从星期日开始算
未完待续……