Date类和SimpleDateFormat和Calendar类的使用

Date 和 SimpleDateFormat 和 Calendar类的使用

Date(我们使用的是util包)

Date d1 = new Date();
//这个代表当前时间
Date d1 = new Date(0);//通过毫秒值创建时间对象
//这个是1970.01.01       0时0分0秒
d1.setTime(1000);	//设置毫秒值,改变时间对象
//一个是通过构造方法改变时间对象,一个是通过set方法改变时间对象

//打印的时间是 8点而非0点,原因是存在操作系统时间和本地时间的问题,其实系统时间依然是0点,只不过我们的电脑时区设置为东八区,故打印的是8点
new Date().getTime();等同于 System.currentTimeMilli();
//前者表示通过时间对象获取毫秒值    后者表示通过系统类的方法获取当前时间的毫秒值

SimpleDateFormat(是DateFormat的子类)

java.text
类 SimpleDateFormat
java.lang.Object
继承者 java.text.Format
继承者 java.text.DateFormat
继承者 java.text.SimpleDateFormat

概念:DateFormat 是时间/日期格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间,是抽象类所有使用其子类SimpleDateFormat

SimpleDateFormat构造方法:

public SimpleDateFormat();//实际用的少
public SimpleDateFormat(String pattern);//一般使用这个

案例:将日期对象转换成字符串

Date d = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

sdf.format(d);//将日期对象转换成字符串

案例: //将时间字符串转换成日期对象

String str = "2019年01月01日 08:00:00";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");//这个地方要跟上面定义的字符串格式匹配

Date date = sdf.parse(str);//将时间字符串转换成日期对象

案例演示你来到这个世界多长时间: (本案例 求的是你的年龄)

String birthDay = "1994/10/14";
String today = "2019/01/04"; 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date birth = sdf.parse(birth);
Date day = sdf.parse(birth);
(birth.getTime()-day.getTime())/1000/60/60/24/365;

Calendar类(java.util 类 Calendar)是抽象类

Calendar cd = Calendar.getInstance();//父类引用指向子类对象
cd.get(Calendar.YEAR);//通过字段获取年
cd.get(Calendar.MONTH);//通过字段获取月,但是月从0开始编号
cd.get(Calendar.DAY_OF_MONTH);//月中的第几天
cd.get(Calendar.DAY_OF_WEEK);//周日是第一天,周六是最后一天

案例:将星期存储表中进行查询定义一个方法

public static String getWeek(int week){
String[] arr = {"","周日","周一","周二","周三","周四","周五","周六"};
return arr[week];
}

案例:打印年月日 周几

cd.get(Calendar.YEAR)+"年"+	(getNum(cd.get(Calendar.MONTH)+1))+"月"+getNum(cd.get(Calendar.DAY_OF_MONTH))+"日"
	+getWeek(cd.get(Calendar.DAY_OF_WEEK));

案例:如果是个数字在前面补0

public static String getNum(int num){
if(num>9){
	return ""+num;
}else{
	return "0"+num;
}
//优化
return num > 9 ? ""+num : "0"+num;
}

成员方法:

public static Calendar getInstance();
public int get(int field);

public void add(int field,int amount);
Calendar cd = Calendar.getInstance();
cd.add(Calendar.YEAR,1);
//表示对指定的字段进行 向前减 或者 向后加
public final void set(int year,int month,int date);
cd.set(Calendar.YEAR,2000);//修改指定字段
cd.set(2000,7,8);//月份7表示8月,月份是从0开始

案例:判断当前年份是平年还是闰年
用Calendar来判断

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int year = Integer.parseInt(line);
boolean b = getYear(year);	
System.out.println(b);

public static boolean getYear(int year){
//创建calendar对象
Calendar cd = Calendar.getInstance();
//设置那一年的3月1日
cd.set(year,2,1);
//将日向前减1
cd.add(Calendar.DAY_OF_MONTH,-1);

return cd.get(Calendar.DAY_OF_MONTH) == 29;
}

猜你喜欢

转载自blog.csdn.net/weixin_41974635/article/details/88111020