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 之日期
最新推荐文章于 2024-08-05 14:21:46 发布
本文深入探讨了Java中Date类、Calendar类和DateFormat类在日期与时间操作方面的应用,包括日期实例化、时间格式化及日期间的基本计算。
1296

被折叠的 条评论
为什么被折叠?



