【蓝桥杯】时间显示--JAVA
解题
1.暴力循环
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long L = scanner.nextLong();
L /= 1000;//题目说毫秒不计
int a = 365*24*60*60;//非闰年一年秒数
int b = 366*24*60*60;//闰年一年秒数
int i = 1970;//起始
String s = "";
while(L/a!=0){//循环减去年份秒数直到只剩一年的秒数
if(i%400==0 || i%4==0&&i%100!=0){
L-=b;
}else {
L-=a;
}
i++;
}
L%=24*60*60;//取余表示最后一天的秒数
int x = (int)L/(60*60);
int y = (int)L%(60*60)/60;
int z = (int)L%(60*60)%60;
if(x>9){
s+=x;
}else {
s+="0"+x;
}
if(y>9){
s+=":"+y+":";
}else {
s+=":"+"0"+y+":";
}
if(z>9){
s+=z;
}else {
s+="0"+z;
}
System.out.println(s);
}
}
2.使用Java自带的毫秒转化时间方式。
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long L = scanner.nextLong();
Date date = new Date();
date.setTime(L);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");//格式化解析日期工具类
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));//这里需要设置时区
String s = sdf.format(date);
String[] s1 = s.split(" ");
System.out.println(s1[1]);
}
}
注意:默认时区是本地时区,我们的默认时区是GMT+8小时,所以应设为GMT标准时区来计算。