Date和Calendar是Java类库里提供对时间进行处理的类,
Date类顾名思义,一看就知道是和日期有关的类了,这个类最主要的作用就是获得当前时间了,
然而这个类里面也具有设置时间以及一些其他的功能,可是由于本身设计的问题,这些方法却遭到众多批评,而这些遭受批评的功能都已移植到Calendar类里面。
一、Date类
1.构造方法
(1)public Date()
创建的日期类对象的日期时间被设置成创建时刻相对应的日期时间。
Date date=new Date(); //today被设置成创建时刻相对应的日期时间。结果:Wed Aug 10 12:03:31 CST 2016
获得当前系统的时间
在该格式中,Sun代表Sunday(周日),Mar代表March(三月),08代表8号,CST代表China Standard Time(中国标准时间,也就是北京时间(东八区))。
(2)public Date (long date)
long 型的参数date可以通过调用Date类中的static方法parse(String s)来获得。
long currentTimeMillis = System.currentTimeMillis();
Date date = new Date(currentTimeMillis);//结果Wed Aug 10 12:14:46 CST 2016
Date类中的static方法parse(String s)
long parse = Date.parse("Wed Aug 10 12:14:46 CST 2016");//结果1470852886000
获取时间戳类型的时间
Date date = new Date();
long time = date.getTime();//time:1470809336850
(3)public Date(String s)
按字符串s产生一日期对象。s的格式与方法parse中字符串参数的模式相同。
Date date=new Date("Wed Aug 10 13:25:17 CST 2016"); //结果Wed Aug 10 13:25:44 CST 2016
2.按给定的参数创建一日期对象。
按:年、月、日
public Date(int year,int month,int date)
按:年、月、日、时、分
public Date(int year,int month,int date,int hrs,int min)
按:年、月、日、时、分、秒
public Date(int year,int month,int date,int hrs,int min,int sec)
参数说明:
year的值为:需设定的年份-1900。例如需设定的年份是1997则year的值应为97,即1997-1900的结果。所以Date中可设定的年份最小为1900;
month的值域为0~11,0代表1月,11表代表12月;
date的值域在1~31之间;
hrs的值域在0~23之间。从午夜到次日凌晨1点间hrs=0,从中午到下午1点间hrs=12;
min和sec的值域在0~59之间。
举例:
Date d1 = new Date(2016-1900,8-1,10);//结果Wed Aug 10 00:00:00 CST 2016
3.获得Date对象中的信息
(这些方法过时了,可以用Calendar类获取)
Date date = new Date();
int year = date.getYear() + 1900;//年份
int month = date.getMonth() + 1;//月份
int dateTime = date.getDate();//日期
int hour = date.getHours();//小时
int minute = date.getMinutes();//分钟
int second = date.getSeconds();//秒
int day = date.getDay();//星期几
结果:
年份:2016
月份:8
日期:Wed Aug 10 13:59:33 CST 2016
小时:13
分钟:59
秒:33
星期:3
使用Date类中对应的get方法,可以获得Date类对象中相关的信息,需要注意的是使用getYear获得是Date对象中年份减去1900以后的值,所以需要显示对应的年份则需要在返回值的基础上加上1900,月份类似。在Date类中还提供了getDay方法,用于获得Date对象代表的时间是星期几,Date类规定周日是0,周一是1,周二是2,后续的依次类推。
4.日期格式化类SimpleDateFormat
Date date = new Date();
SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(myFmt.format(date));
System.out.println(myFmt2.format(date));
结果:
2016年08月10日 16时19分30秒
2016-08-10 16:19:30
关于更多DateFormat类和SimpleDateFormat类介绍,这篇很详细超赞http://www.jb51.net/article/84104.htm点击打开链接
本文章参考
http://blog.csdn.net/wguoyong/article/details/7417205
http://cruih.iteye.com/blog/1098327
http://www.2cto.com/kf/201209/158192.html