package chapter6;import java.text.dateformat;import java.text.parseexception;import java.util.*;public class ioelseclass { //date类的大多数方法已经不推荐使用了,它现在主要用作calendar类和format类的桥梁 //在内部,日期和时间被存储为long类型,表示的日期是与1970.1.1之间的毫秒数(1万亿毫秒==31年8个月) public void datemethod(){ date d1 =new date(1000000000000l); system.out.println("1st "+d1.tostring());//tostring()方法默认已经被重写过了 d1.settime(d1.gettime()+3600000);//1hour=3600s system.out.println("2st "+d1.tostring()); date nowdate =new date();//无变元构造函数,返回的是当前时间 system.out.println("3st "+nowdate.tostring()); //output is: //1st sun sep 09 09:46:40 gmt+08:00 2001 //2st sun sep 09 10:46:40 gmt+08:00 2001 //3st sat may 22 11:53:55 gmt+08:00 2010 } //calendar类,字段按域考虑 public void calendarmethod(){ date d1 =new date(); system.out.println(d1.tostring()); calendar c =calendar.getinstance(); c.settime(d1);//calendar.sunday,返回的是int值==1 if(calendar.sunday == c.getfirstdayofweek()){//如果是美国的星期制 system.out.println("sunday is the first day of the week"); } system.out.println("the day of week is "+c.get(calendar.day_of_week));//星期几其实是一周的第几天 system.out.println(c.get(calendar.year)+" "+c.get(calendar.month)+" "+c.get(calendar.date));//月份的起始值是0 c.add(calendar.month, 1);//前面是域,后面是值 system.out.println(c.get(calendar.year)+" "+c.get(calendar.month)+" "+c.get(calendar.date)); date d2 =c.gettime();//返回已被修改的date对象 system.out.println(d2.tostring()); //略roll方法,增加的数,不会递增。(exp:增加月数超12了,不会对年数产生增加) //output is: //sat may 22 12:28:49 gmt+08:00 2010 //sunday is the first day of the week //the day of week is 7 //2010 4 22 //2010 5 22 //tue jun 22 12:28:49 gmt+08:00 2010 } //dateformat类,格式化日期 public void dateformatmethod(){//dateformat在java.text包里 date d1 =new date(); system.out.println("d1 ="+d1.tostring()); dateformat df =dateformat.getdateinstance(dateformat.short);//如果需要记住时间,要调用getdatetimeinstance() string s=df.format(d1); system.out.println("s ="+s.tostring()); try { date d2 =df.parse(s); system.out.println("d2 ="+d2.tostring()); } catch (parseexception e) { e.printstacktrace(); } //output is: //d1 =sat may 29 20:24:14 gmt+08:00 2010 //s =10-5-29 //d2 =sat may 29 00:00:00 gmt+08:00 2010 } //略locale和numberformat public static void main(string[] args) { ioelseclass iec =new ioelseclass(); //iec.datemethod(); //iec.calendarmethod(); //iec.dateformatmethod(); }}
chapter 6 之日期
最新推荐文章于 2025-08-06 16:23:50 发布