Calendar类及相关方法
发布时间:2021-05-20 09:45:22 所属栏目:大数据 来源: https://blog.csdn.net/summoxj
导读:import java.util.Calendar; import java.util.Date; /* ?* Calendar类写了静态方法getInstance()直接返回了子类的对象 ?* 不需要直接new子类的对象,通过静态方法直接获取 ?*/ public class CalendarDemo { ?? ?public static void main(String[] args) { ?
import java.util.Calendar; /* ?* Calendar类写了静态方法getInstance()直接返回了子类的对象 ?* 不需要直接new子类的对象,通过静态方法直接获取 ?*/ public class CalendarDemo { ?? ?public static void main(String[] args) { ?? ??? ?Calendar c=Calendar.getInstance(); ?? ??? ?System.out.println(c); ?? ??? ? ?? ??? ?function(); ?? ??? ? ?? ??? ?function_1(); ?? ??? ? ?? ??? ?function_2(); ?? ??? ? ?? ??? ?function_3(); ?? ?} ?? ? ?? ?//获取日历字段的值 ?? ?public static void function(){ ?? ??? ?Calendar c=Calendar.getInstance(); ?? ??? ?//获取年份 ?? ??? ?int year= c.get(Calendar.YEAR); ?? ??? ?//获取月份 ?? ??? ?int month=c.get(Calendar.MONTH)+1; ?? ??? ?//获取天数 ?? ??? ?int day=c.get(Calendar.DAY_OF_MONTH); ?? ??? ?System.out.println(year+"年"+month+"月"+day+"日"); ?? ?} ?? ? ?? ?/*设置日历 ?? ? *set(int field,int value) field:设置的是哪个日历字字段,value:设置后的具体数值 ?? ? *set(int year,int month,int day) 传递3个整数的年,月,日 ?? ? */ ?? ?public static void function_1(){ ?? ??? ?Calendar c=Calendar.getInstance(); ?? ??? ?//设置,月份,10月 ?? ??? ?c.set(Calendar.MONTH,9); ?? ??? ?//设置年,月,日 ?? ??? ?c.set(2099,4,1); ?? ??? ?//获取年份 ?? ??? ??? ??? ?int year= c.get(Calendar.YEAR); ?? ??? ??? ??? ?//获取月份 ?? ??? ??? ??? ?int month=c.get(Calendar.MONTH)+1; ?? ??? ??? ??? ?//获取天数 ?? ??? ??? ??? ?int day=c.get(Calendar.DAY_OF_MONTH); ?? ??? ??? ??? ?System.out.println(year+"年"+month+"月"+day+"日"); ?? ?} ?? ? ?? ?/* Calendar类方法add ?? ? * 日历的偏移量,可以指定一个日历中的字段,进行整数的偏移 ?? ? * add(int field,int value) ?? ? */ ?? ?public static void function_2(){ ?? ??? ?Calendar c=Calendar.getInstance(); ?? ??? ?//让日历中的天数,向后偏移280天 ?? ??? ?c.add(Calendar.DAY_OF_MONTH,280); ?? ??? ?//获取年份 ?? ??? ?int year= c.get(Calendar.YEAR); ?? ??? ?//获取月份 ?? ??? ?int month=c.get(Calendar.MONTH)+1; ?? ??? ?//获取天数 ?? ??? ?int day=c.get(Calendar.DAY_OF_MONTH); ?? ??? ?System.out.println(year+"年"+month+"月"+day+"日"); ?? ?} ?? ? ?? ?//Calendar类的方法getTime(),把日历对象,转成Date对象 ?? ?public static void function_3(){ ?? ??? ?Calendar c=Calendar.getInstance(); ?? ??? ?Date date=c.getTime(); ?? ??? ?System.out.println(date); ?? ?} } (编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |