Java日期时间处理

时间:2022-04-13 23:52:58

Date类的使用

类Date表示特定的瞬间,精确到毫秒,从JDK 1.1开始,应该使用Calendar类实现日期和时间字段之间转换

常用方法:

1.getTime():返回自1970年1月1日00:00:00以来Date对象表示的毫秒

2.setTime():设置时间,以表示自1970年1月1日00:00:00以来的时间点

基本使用:

Date d=new Date();
System.out.println(d);//输出Wed Jun 11 09:22:30 CST 2016 注意:CST:中国标准是时间

Calendar类的使用

Calendar 类是一个抽象类,,瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年1月1日的 00:00:00.000)的偏移量

基本使用:

Calender c=Calender.getInstance();//使用默认时区和语言环境获得一个日历

c.setTime(new Date());
Date date=c.getTime();//将Calender对象转换为Date对象

int year=c.get(Calender.YEAR);//年
int month=c.get(Calender.MONTH)+1;//0表示1月份
int day=c.get(Calender.DAY_OF_MONTH);//获得日期
c.add(Calendar.DAY_OF_MONTH, -1);//取当前日期的前一天
c.add(Calendar.DAY_OF_MONTH, +1);//取当前日期的后一天
int hour=c.get(Calender.HOUR_OF_DAY);//获得小时
int minute=c.get(Calender.MINUTE);//获得分钟
int second=c.get(Calender.SECOND);//获得秒

Long time=c.getTimeInMillis();//获得当前毫秒数

SimpleDateFormat类的使用:

该类位于java.text.SimpleDateFormat中

基本使用:

Date d=new Date();
SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置格式
String time=s.format(d);//输出:2016-06-11 09:55:48

String s1="2012-01-29-22-26-23";
String pattern ="yyyy-MM-dd-HH-mm-ss";
SimpleDateFormat sdf1 =new SimpleDateFormat(pattern);
Date date1 = sdf1.parse(s1);//parse()方法用于将输入的特定字符串转换成Date类的对象

上面的那个日期和时间模式,是按我们常用的年月日时分秒来放的,下面传个别人的专业的图,供参考:

Java日期时间处理

DateFormat类的使用

该类位于java.text.DateFormat中

基本使用:

DateFormat a=new SimpleDateFormt("yyyy年MM月dd日,属于第W周");
Date b=new Date(12415154664446L);
String c=a.format(b);//输出1962年4月日,属于第1周

GregorianCalendar类的使用:

GregorianCalendar(标准阳历)是Calendar的一个实现大家所熟悉的标准日历的具体工具,.它是Calendar类的一个具体子类,提供了大多数国家/地区的标准日历系统

基本使用:

Calendar c=new GregorianCalendar();
c.set(2016(年),Calendar.JUNE(6月),30(日),20(时),59(分),30(秒));
c.set(Calendar.YEAR,2016);//年
c.set(Calender.MONTH,3);//月
c.add(Calendar.MONTH,3);//增加3月为6
c.setTime(new Date());//注意:其他没设置的输出当前时间
Date d=c.getTime();