日期类常用的有三个,date类,calendar(日历)类和日期格式转换类(dateformat)
date类中的大部分的方法都已经过时,一般只会用到构造方法取得系统当前的时间。
public class datedemo {
public static void main(string[] args) {
date date = new date();
system.out.println(date);
}
}
结果输出当前系统的时间:fri mar 10 16:50:37 cst 2017
我们可以看到,这种格式的时间我们看着并不习惯,所以在展示时间的时候必须要转换一下输出格式,这时候我们要用到日期格式转换类dateformat了。
public class formatdemo {
public static void main(string[] args) {
date d=new date();
system.out.println(d);
format f=new simpledateformat("yyyy-mm-dd hh-mm-ss");
string s=f.format(d);
system.out.println(s);
}
}
这时输出时间为:2017-03-10 04-54-06
这样就看着很舒服了。
calendar
calendar 类是一个抽象类,它为特定瞬间与一组诸如 year、month、day_of_month、hour 等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
可以使用三种方法更改日历字段:set()、add() 和 roll()。
1,set(f, value) 将日历字段f 更改为value。
2,add(f, delta) 将delta 添加到f 字段中。
3,roll(f, delta) 将delta 添加到f 字段中,但不更改更大的字段。
public class test {
public static void main(string[] args) {
calendar c=new gregoriancalendar();
c.set(calendar.day_of_month,1);
system.out.println("输出的是本月第一天");
system.out.println((c.get(calendar.march)+1)+"月的"+c.get(calendar.day_of_month)+"号");
c.roll(calendar.day_of_month,-1);
system.out.println("输出的是本月最后一天");
system.out.println((c.get(calendar.march)+1)+"月的"+c.get(calendar.day_of_month)+"号");
}
}
输出结果为:
输出的是本月第一天
3月的1号
输出的是本月最后一天
3月的31号
roll方法在操作的过程中,一号天数减一之后,直接又返回本月的最后一天,日期变动在本月内循环而不会去改变月份,即不会更改更大的字段。
比较add方法:
public class test {
public static void main(string[] args) {
calendar c=new gregoriancalendar();
c.set(calendar.day_of_month,1);
system.out.println("输出的是本月第一天");
system.out.println((c.get(calendar.march)+1)+"月的"+c.get(calendar.day_of_month)+"号");
c.add(calendar.day_of_month,-1);
system.out.println("输出的是上个月最后一天");
system.out.println((c.get(calendar.march)+1)+"月的"+c.get(calendar.day_of_month)+"号");
}
}
输出结果为:
输出的是本月第一天
3月的1号
输出的是本月最后一天
2月的28号
可以看出在三月一号的基础上减去一之后,自动月份自动变到了二月。这个时roll方法和ad方法的区别。
以上就是java中的常用日期类说明的详细内容。
