通常在处理时分秒问题时候会涉及到以下问题:
时分秒转秒,秒转时分秒
整数版
static int toSeconds(int h, int m, int s){ return h * 3600 + m * 60 + s; }字符串版
static int toSeconds(String t){ String[] a = t.split(":"); int h = Integer.parseInt(a[0]); int m = Integer.parseInt(a[1]); int s = Integer.parseInt(a[2]); return h * 3600 + m * 60 + s; }输出模版(时分秒整数转String)
static String toTime(int x){ int h = x / 3600; x %= 3600; int m = x / 60; int s = x % 60; return String.format("%02d:%02d:%02d", h, m, s); }判断时分秒是否合法
有些题会比较坑,时分秒要判断一下
static boolean isLegal(int h, int m, int s){ return h >= 0 && h < 24 && m >= 0 && m < 60 && s >= 0 && s < 60; }时差
同一天时差
int diff = Math.abs(t2 - t1);跨天时差
int diff; if(t2 >= t1) diff = t2 - t1; else diff = 24 * 3600 - t1 + t2;当时间跨度超过一天就要清零,比如23:59:50是86390秒,再加20秒不能让时间出现86410,必须模一下清零之前的时间变为10秒
t = (t + N) % (24 * 3600);去回程时差
int fly = ((t2 - t1) + (t4 - t3)) / 2;下面解释一下各个变量的含义
由于地区是有时差的,所以在各个地方算时差不准,把来去时间做和就可以消去时差