引入:
在不断的学习中,我们会不断地掌握一些新知识,可以更好地帮助我们解决一些难题。就像我们高中的时候求法向量,我们会先假设平面法向量为n=(x, y, z),然后和已知两个平面向量联立求解x, y, z各是多少,进而求出法向量。这是高中时期常见的解法,可当我们进入大学之后我们会发现,可以直接用两个向量叉乘用一个三阶行列式直接进行求解,速度更快,更有助于我们解决问题。而今天的主角就是Java时间API。
当我还没学习API的时候,我在做时间计算的时候,是先把时间存在一个数组中然后根据时间的转换关系,再对时间进行加减,这样不仅麻烦不说,还很容易出错。今天我就对时间计算这题旧题新做,用更简单的方法,更高效的方法。
想看我之前是如何做的可以查看我往期作品。
题目描述
定义一个时间类MyTime,实现时间(小时、分钟、秒)的输入、输出、相关计算、比较等功能。时间的计算包括但不限于:
时间相加:从t1时刻经过t2时间后得到的新时间;
时间相减:t1时刻的t2时间之前的时间,这也是一个新时间;(例如:10时34分之前50分钟的时间是什么)
两个MyTime时间对象之间的间距:运算结果单位为秒。
输出:格式为“时:分:秒”
定义主类MyTimeTest(OJ上提交时修改为Main),按照输入的时、分、秒分别创建两个时间类的对象t1与t2,输入m分或m时或m秒,输出t1+m、t1-m与t2-t1的运算结果。
说明1:两个字符串s1与s2比较是否相同,使用的是s1.equals(s2),若内容相同则返回true,否则返回false。
说明2:字符串s获取子串,String r=s.substring(begin,end),例如,s串为”123s“,则String s1=s.substring(s.length()-1); String s2=s.substring(0, s.length()-1); ,经过处理后,s1为”s”,s2为”123”。
说明3:将字符串s,s为”123”转换为整数123的方法是:int n=Integer.parseInt(s);
说明4:注意时、分、秒的取值范围
说明5:最后一行输入,小时用h表示、分钟用m表示、秒用s表示。
输入
三行,两组时间,一个时间间隔
输出
三行,计算后的两组时间,时间间隔
样例输入 Copy
16 25 35 13 20 30 80s
样例输出 Copy
16:26:55 16:24:15 -11105s
本代码运用了LocalDate, DateTimeFormatter, Duration三个常用API,不会的朋友可以查查是如何用的
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class Main {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
LocalTime lt_1 = LocalTime.of(input.nextInt(), input.nextInt(), input.nextInt());
LocalTime lt_2 = LocalTime.of(input.nextInt(), input.nextInt(), input.nextInt());
String s = input.next();
int n = MyTime.conversionTime(s);
MyTime.addTime(lt_1, n);
MyTime.subTime(lt_1, n);
MyTime.timeSubTime(lt_1, lt_2);
}
}
class MyTime{
public static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
public static int conversionTime(String s) {
String s1;
String s2;
s1 = s.substring(s.length()-1);
s2 = s.substring(0, s.length()-1);
int n = Integer.parseInt(s2);
switch(s1) {
case "s": break;
case "m": n *= 60; break;
case "h": n *= 3600; break;
}
return n;
}
public static void addTime(LocalTime dt, int n) {
LocalTime dt_2 = dt.plusSeconds(n);
String sTime = formatter.format(dt_2);
System.out.println(sTime);
}
public static void subTime(LocalTime dt, int n) {
LocalTime dt_2 = dt.plusSeconds(-1*n);
String sTime = formatter.format(dt_2);
System.out.println(sTime);
}
public static void timeSubTime(LocalTime dt, LocalTime dt2) {
Duration drTime = Duration.between(dt, dt2);
long n = drTime.toSeconds();
System.out.println(n + "s");
}
}