您的位置:首页 > 编程语言 > Java开发

20160126--日期类

2016-01-26 13:45 274 查看
Date类

①getTime方法

返回长整数,代表从1970年1月1日开始到Date对象中的时间之间的毫秒数,与System.currentTimeMillis()返回值相同。
/** 
 * 计算n年前的日期 
 */ 
Date myDate = new Date(); 
long myTime = (myDate.getTime() / 1000) - 60 * 60 * 24 * 365 * n; myDate.setTime(myTime * 1000); 
System.out.println(myDate);

②after
用于测试此日期对象是否在指定日期之后。
public boolean after(Date when)
当此Date对象表示的时间比when表示的时间晚,返回true;否则返回false。
before同上

③compareTo
int x = onedate.compareTo(Date anotherDate);
如果参数anotherDate表示的时间等于当前Date对象表示的时间,方法返回值为0;如果当前Date对象表示的时间anotherDate参数表示的时间之前,则返回-1;如果当前Date对象在anotherDate参数表示的时间之后,则返回1。

④DateFormat类
DateFormat df = null; // 声明DateFormat类对象 
df = DateFormat.getDateInstance(); // 日期格式器 
df = DateFormat.getDateTimeInstance(); // 日期时间格式器
df1.format(new Date())

⑤SimpleDateformat类
SimpleDateFormat myFmt = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
System.out.println(myFmt.format(d));
//将指定字符串转换成日期
SimpleDateFormat myFmt = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
System.out.println(myFmt.format(d));

⑥Calendar类
用于表示所有日历的模板,其本身是抽象类,定义了所有日历类通用的方法。
Calendar类和Date类的相互关系:
Calendar cal1 = Calendar.getInstance();
Date date1 = cal1.getTime(); //转化为Date
System.out.println(date1);
Date date2 = new Date();
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2); //用Date初始化Calendar

Calendar calendar = Calendar.getInstance();
"当前日期:"calendar.getTime();
"年:"calendar.get(Calendar.YEAR);
"月:"calendar.get(Calendar.MONTH) + 1); 
"日:"calendar.get(Calendar.DAY_OF_MONTH);
"时:" + calendar.get(Calendar.HOUR_OF_DAY); 
"分:" + calendar.get(Calendar.MINUTE); 
"秒:" + calendar.get(Calendar.SECOND);
"毫秒:"+calendar.get(Calendar.MILLISECOND);
//计算某月最大天数
Calendar time = Calendar.getInstance(); 
time.set(Calendar.YEAR, year); // year 为 int 
time.set(Calendar.MONTH, month - 1);// Calendar对象默认一月为0 
int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);// 本月份天数

⑦java.sql.Date类

java.sql.Date是java.util.Date类的子类,是针对SQL语句使用的,默认只输出日期而没有时间部分。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java日期类