一、回文日期
1.LocalDate类
1)获取方法
LocalDate now = LocalDate.now(); // 获取当前日期
int year = now.getYear(); // 获取年份
int month = now.getMonthValue(); // 获取月份
int time1 = now.getDayOfMonth(); // 获取月份中的第几天
int time2 = now.getDayOfYear(); // 获取一年中的第几天
int time3 = now.lengthOfYear(); // 获得当年总天数
int time4 = now.lengthOfMonth(); // 获得当月总天数
2)修改方法
LocalDate now = LocalDate.now();
LocalDate now1 = now.withYear(2003); // 修改日期对象年份为2003
LocalDate now2 = now.withMonth(12); // 修改日期对象月份为12
LocalDate now3 = now.withDayOfMonth(1); // 修改日期对象的日期(一月中的第几天)
LocalDate now4 = now.withDayOfYear(1); // 修改日期对象的日期(一年中的第几天)
3)运算方法
LocalDate now = LocalDate.now();
LocalDate now1 = now.plusDays(1); // 给当前时间加一天
LocalDate now2 = now.plusWeeks(1); // 给当前时间加一周
LocalDate now3 = now.plusMonths(1); // 给当前时间加一月
LocalDate now4 = now.plusYears(1); // 给当前时间加一年
LocalDate now5 = now.minusDays(1); // 给当前时间减一天
LocalDate now6 = now.minusWeeks(1); // 给当前时间减一周
LocalDate now7 = now.minusMonths(1); // 给当前时间减一月
LocalDate now8 = now.minusYears(1); // 给当前时间减一年
2.应用
String str = scan.nextLine(); //输入一个字符串
int year = Integer.parseInt(str.substring(0, 4)); //substring是字符串截取的方法
int month = Integer.parseInt(str.substring(4, 6)); //parseInt是将字符串转换为整形的方法
int day = Integer.parseInt(str.substring(6,8));
输入日期如“20200202”,其中str="20200202",year=2020,month=02,year=02;
LocalDate date = LocalDate.now();//获取当前日期
date = date.withYear(year);//修改日期年份为year
date = date.withMonth(month);//修改日期对象月份为month
date = date.withDayOfMonth(day);//修改日期对象的日期(month月中的第day天)
date = date.plusDays(1);//将data时间加一天
以上方法就用到了LocalDate中的的修改方法和运算方法
实现以上代码后,date的日期就变为:2020年2月3日
二、航班时间
1.Date类的getTime()方法
getTime方法返回的是一个13位数字,单位是毫秒。除1000能让单位变为秒。
2.SimpleDateFormat类
SimpleDateFormat类属于 java.text
包,用于格式化和解析日期和时间。允许将日期和时间对象转换成字符串表示,或者将字符串解析成日期和时间对象。
1)创建对象
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
以上创建的对象指定了日期时间的格式为 “yyyy-MM-dd HH:mm:ss”
2)将日期和时间转换成字符串
可以使用它的 format()
方法将日期和时间对象格式化成字符串
Date now = new Date(); // 获取当前日期和时间
String str = format.format(now);
3)将字符串解析成日期和时间
可以使用 parse()
方法将字符串解析成日期和时间
String str = "2024-01-14 17:14:36";
Date date = format.parse(str);
3.应用
String line = scan.nextLine();//读取字符串,即时间
String[] split = line.split(" ");//把字符串分割成字符串数组,根据" "划分
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
输入字符串,并创建一个SimpleDateFormat对象,格式为"HH:mm:ss"
例如输入“17:48:19 21:57:24”,line = "17:48:19 21:57:24"
split[0]="17:48:19" split[1]="21:57:24"
Date t1 = format.parse(split[0]);//17:48:19
Date t2 = format.parse(split[1]);//21:57:24
运用对象format的parse方法将字符串解析成时间
long time1 = t1.getTime()/1000;
long time2 = t2.getTime()/1000;
运用Date的getTime方法得到长整形,单位为秒