Calendar calendar=Calendar.getInstance();//创建一个日历对象 int year=calendar.get(calendar.YEAR);//获取当前年份 System.out.println("获取当前年份:"+year);
int month=calendar.get(calendar.MONTH)+1;//获取月份 System.out.println("获取月份:"+month);
int date=calendar.get(calendar.DATE);//获取日期 System.out.println("获取日期:"+date);
int huor=calendar.get(calendar.HOUR);//获取时 System.out.println("获取时:"+huor);
int hous=calendar.get(calendar.HOUR_OF_DAY);//获取时的24小时制 System.out.println("获取时的24小时制:"+hous);
//将给定的日历字段设置为给定的值 calendar.set(calendar.YEAR,2034);//设置指定年份 int year2=calendar.get(calendar.YEAR);//获取设置指定年份 System.out.println("获取设置指定年份:"+year2);
calendar.set(calendar.MONTH,5);//设置指定月份 int month2=calendar.get(calendar.MONTH);//获取设置的指定月份 System.out.println("获取设置的指定月份:"+month2);
calendar.set(calendar.DATE,5);//设置指定日子 int date2=calendar.get(calendar.DATE);//获取指定日 System.out.println("获取指定日:"+date2);
Calendar年份增加两年
Calendar月份减少三月
1 2 3 4 5 6
// 根据日历规则,为给定的日历字段添加或者减去指定的事件量 calendar.add(calendar.YEAR,2);//把年份增加两年 calendar.add(calendar.MONTH,-3);//把月份减少三年 int yuer=calendar.get(calendar.YEAR); int month3=calendar.get(calendar.MONTH); System.out.println(yuer+"年"+month3+"月"+date+"日");
// 获取日期的年月日周时分秒 LocalDateTime lodatm=LocalDateTime.now(); int dayYear=lodatm.getDayOfYear(); int dayMonth=lodatm.getDayOfMonth(); DayOfWeek dayofweek=lodatm.getDayOfWeek(); System.out.println("\n\n今天是:"+lodatm+"\n" + "本年当中的第"+dayYear+"天\n" + "本月当中的第"+dayMonth+"天\n" + "本周中的星期"+dayofweek.getValue()+"及"+dayofweek+"\n");
//获取当天时间的年月日时分秒 int year2=lodatm.getYear(); Month month2=lodatm.getMonth(); int day=lodatm.getDayOfMonth(); int hour=lodatm.getHour(); int minute=lodatm.getMinute(); int secound=lodatm.getSecond(); System.out.println("\n\n今天是:"+lodatm+"\n年:"+year2+"\n月:"+month2.getValue()+"\n" + "日:"+day+"\n时:"+hour+"\n分:"+minute+"\n秒:"+secound);
LocalDate date1=LocalDate.of(2018,3,3); LocalDate date2=LocalDate.of(2023,6,6); Period per=Period.between(date1,date2); System.out.println("相差年数:"+per.getYears()); System.out.println("相差月份:"+per.getMonths()); System.out.println("相差日数:"+per.getDays());
System.out.println("\n==================================="); long years=per.get(ChronoUnit.YEARS); long month=per.get(ChronoUnit.MONTHS); long days=per.get(ChronoUnit.DAYS); System.out.println("相差的年月日分别为:"+years+"-"+month+"-"+days);
// 将Instant对象转换为时间戳 long insTime=Instant.now().toEpochMilli(); System.out.println("Instant时间戳:"+insTime);
Date date=Date.from(ins); Instant instant=date.toInstant(); System.out.println(instant);
//将LocalDateTime对象转换为时间戳 long loTime=lo.toInstant(ZoneOffset.of("+8")).toEpochMilli(); System.out.println("LocalDateTime时间戳:"+loTime);
//将Date对象转换为时间戳 Date date4=newDate(); long dateTime=date4.getTime(); System.out.println("Date时间戳:"+dateTime);
long calTime=calendar.getTimeInMillis();//第一种方法 System.out.println("Calendar时间戳1:"+calTime); System.out.println("Calendar时间戳2:"+calendar.getTime().getTime());//第二种方法