Date date1 = new Date();
Date date2 = new Date(long l);
Date date3 = new Date(int year, year month, int day);
其中第三种已经过时了。
Date date1 = new Date();
Date date2 = new Date(2000, 11, 20);
Date date6 = new Date(60935385600000L);//值分别是
//Thu Jun 22 10:58:45 CST 2017
//Thu Dec 20 00:00:00 CST 3900
//Thu Dec 20 00:00:00 CST 3900
日期是不是在参数前,返回boolean
boolean before = date1.before(date2);// true
boolean after = date1.after(date2);// false
复制日期
Date date3 = (Date) date1.clone()
date1
和date3
是相等的。
比较2个日期,返回int。
apateTo(b)若a在b前,返回负数;若a在b后,返回整数;若相等,返回0;正负数一般是-1,1。
int compareTo1 = date1pareTo(date2);// -1
int compareTo2 = date1pareTo(date3);// 0
int compareTo3 = date1pareTo(date4);// 1
比较日期是否相等,返回boolean。
boolean equals1 = date1.equals(date2);// false
boolean equals2 = date1.equals(date3);// true
Date转long
long time1 = Time();
long time2 = Time();
long转Date
Date date5 = new Date(time1);
格式化日期的类。
SimpleDateFormat sdf1 = new SimpleDateFormat();
SimpleDateFormat sdf1 = new SimpleDateFormat(Strign pattern);
pattern
一般有
"YYYY-mm-dd HH:mm:ss"
将Date格式化为我们需要的样式String,将String类型的日期转成Date,需要用到2个方法
format(date1);
parse(String);
format():
Date转换成String类型的日期
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = sdf1.format(date1);// 2017-06-22 13:54:11
String类型的日期转换成Date
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse1 = sdf1.parse("2017-06-22 11:59:40");
采用printf()
格式化日期,已%t
开始,%n
表示换行
System.out.printf("%tc%n", date1); // 星期四 六月 22 14:38:08 CST 2017
System.out.printf("%tF%n", date1);// 2017-06-22
System.out.printf("%tD%n", date1);// 06/22/17
System.out.printf("%tr%n", date1);// 02:41:40 下午
System.out.printf("%tT%n", date1);// 14:41:40
System.out.printf("%tR%n", date1);// 14:41
让线程休眠,可以计算耗时
int sum = 0;
long time5 = System.currentTimeMillis();
try {Thread.sleep(3000);
} catch (InterruptedException e) {e.printStackTrace();
}
long time6 = System.currentTimeMillis();
System.out.println("耗时:" + (time6 - time5));
日历,可以和方便的设置日期和时间,获取年月日等数据。
Calendar
是个抽象类
Calendar calendar = Instance();
月份是从0-11,也就是说0是一月;11是十二月。
calendar.setTime(date1);
calendar.setTimeInMillis(1234567890l);
calendar.set(2008, 8, 8, 8, 8,8);//9月
calendar.set(2008, 8, 8);
也可以值设置当个字段
calendar.set(Calendar.YEAR, 2008);
calendar.set(Calendar.MONTH, 8);
calendar.set(Calendar.DAY_OF_MONTH, 8);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.SECOND, 8);
add()
某个字段加数字,可以是负数。正数表示日期加,负数表示日期减。
月份提前2个月
calendar.add(Calendar.DAY_OF_MONTH, -2);
获取年份
int year = (Calendar.YEAR);
Date date = Time();
是Calendar的子类
GregorianCalendar gregorianCalendar = new GregorianCalendar();
Date time = Time();
本文发布于:2024-02-01 01:41:21,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170672287932932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |