package com.zuxia.test;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Scanner;
import org.junit.Test;
public class TestHome {
@Test
public void test1() {
//控制台接收输入的日期(年月日),使用新的日期时间API完成日历表打印
Scanner sc=new Scanner(System.in);
System.out.print("请输入一个日期:");
String strDate=sc.next();
//将接收到的日期字符串转换为日期对象
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate ld=LocalDate.parse(strDate, dtf);
//获取总的天数 以及 1号对应的星期数
int lastDay = ld.lengthOfMonth();
DayOfWeek dow = ld.with(TemporalAdjusters.firstDayOfMonth()).getDayOfWeek();
//遍历打印
System.out.println("日\t一\t二\t三\t四\t五\t六");
int count=0;
if(dow==DayOfWeek.MONDAY) {
count=1;
}else if(dow==DayOfWeek.TUESDAY) {
count=2;
}else if(dow==DayOfWeek.WEDNESDAY) {
count=3;
}else if(dow==DayOfWeek.THURSDAY) {
count=4;
}else if(dow==DayOfWeek.FRIDAY) {
count=5;
}else if(dow==DayOfWeek.SATURDAY) {
count=6;
}
for(int i=0;i<count;i++) {
System.out.print("\t");
}
for(int i=1;i<=lastDay;i++) {
System.out.print(i+"\t");
count++;
if(count>=7) {
System.out.println();
count=0;
}
}
}
@Test
public void test2() {
//动态接收2个日期时间,获取日期时间差(输出格式:两个时间相差X年X月X天 X小时X分钟X秒)
Scanner sc=new Scanner(System.in);
System.out.print("请输入第一个日期:");
String startDate=sc.nextLine();
System.out.print("请输入第二个日期:");
String endDate=sc.nextLine();
//转换
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime start=LocalDateTime.parse(startDate, dtf);
LocalDateTime end=LocalDateTime.parse(endDate, dtf);
//获取日期/时间差
Period per=Period.between(start.toLocalDate(), end.toLocalDate());
Duration dur=Duration.between(start.toLocalTime(), end.toLocalTime());
//获取差值
int year=per.getYears();
int month=per.getMonths();
int day=per.getDays();
long hour=dur.toHours();
long minutes=dur.minusHours(dur.toHours()).toMinutes();
long second=dur.minusMinutes(dur.toMinutes()).getSeconds();
System.out.println("两个日期时间相差:"+year+"年"+month+"月"+day+"天 "+hour+"小时"+minutes+"分钟"+second+"秒");
}
}
用 Java8 新的日期时间API完成小案例
最新推荐文章于 2023-02-26 17:18:45 发布