按要求完成下面的代码
1.定义一个时间字符串"2000-08-08 08:08:08"
2.使用LocalDateTime的parse方法,解析为LocalDateTime对象
3.求这一年是平年还是闰年
提示:把LocalDateTime的时间设置到2000年的3月1日,再减1天就到了二月的最后一天。
再获取这一天的是几号,如果是28就是平年,否则就是闰年*/
public class Test3 {
public static void main(String[] args) {
//创建对象:定义格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//调用方法的格式,吧时间字符串解析为 LocalDateTime对象
LocalDateTime parse1 = LocalDateTime.parse("2000-08-08 08:08:08", dateTimeFormatter);
//在调用 LocalDateTime的设置日期方法,巴月份设置为3月
LocalDateTime localDateTime = parse1.withMonth(3);
//在调用 LocalDateTime的设置日期方法,把日期设置为1号
LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(1);
//在调用 LocalDateTime的设置日期方法,吧天数-1天
LocalDateTime localDateTime2 = localDateTime1.plusDays(-1);
//调用方法 得到当前的天数在月份里是多少号
int dayOfMonth = localDateTime2.getDayOfMonth();
if (dayOfMonth!=28){
System.out.println("今年是平年");
}else{
System.out.println("今年是闰年");
}
}
}
键盘录入你的生日:1996年8月8日
2.使用LocalDate和Period求你的年龄是多少?
(JDK8的API)
public class Test1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入您的生日:格式为xxxx-xx-xx");
String str=sc.next();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//调用LocalDate的parse方法,传入日期字符串和时间格式
LocalDate localDate = LocalDate.parse(str, dateTimeFormatter);
LocalDate now = LocalDate.now();
Period p = Period.between(localDate, now);
int years = p.getYears();
System.out.println("年龄为:"+years);
设定一个抽奖的时间,如:"2021年11月11日 10点00分00秒"
2. 把抽奖时间解析为LocalDateTime对象
3. 计算当前时间和抽奖时间的时间间隔,还有xx天xx小时xx秒
public class Test4 {
public static void main(String[] args) {
while (true) {
//调用LocalDateTime的of方法,定义时间对象
LocalDateTime localDateTime = LocalDateTime.of(2021, 11, 11, 10, 00, 00);
//调用LocalDateTime的now方法,获取现在的系统时间
LocalDateTime localDateTime1 = LocalDateTime.now();
//调用Duration的betwween方法,算出两个时间的差值
Duration between = Duration.between(localDateTime1, localDateTime);
//获取相隔的小时
long day = between.toDaysPart();
int hour = between.toHoursPart();
int min = between.toMinutesPart();
int second = between.toSecondsPart();
System.out.println("距离双十一还有:"+day+"天"+hour+"小时"+min+"分钟"+second+"秒");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}