大一新生,看到相关书籍有这道题,要用System.currentTimeMillis() 获取当前时间
网上似乎都是创建Date或者Calender对象
我想了想还是用最原始的方法写吧~
代码如下,大神有问题可以指出~
public class Time {
public static void main(String[] args) {
long seconds = System.currentTimeMillis() / 1000; //获取的时间为毫秒(1s = 1000ms)
long currentSecond = seconds % 60;
long minutes = seconds / 60;
long currentMinute = minutes % 60;
long hours = minutes / 60;
long currentHour = hours % 24;
long days = hours / 24 + 1; // 加上一天
// 获取年份
int year = 1970; //System.currentTimeMillis() 是从1970年1月1日0时开始计算
while (days >= (isLeapYear(year) ? 366 : 365)) {
days = days - (isLeapYear(year) ? 366 : 365);
year++;
}
// 获取月份
int month = 1;
while (days >= getNumberOfDaysInMonth(year, month)) {
days = days - getNumberOfDaysInMonth(year, month);
month++;
}
System.out.println("当前时间为 "
+ year + "年" +month + "月" + days + "日 "
+ (currentHour+8) + ":" + currentMinute + ":" + currentSecond); //currentHour+8是因为算的是0时区,而中国是东八区所以加8
}
//获取具体的日数
public static int getNumberOfDaysInMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12)
return 31;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2) return isLeapYear(year) ? 29 : 28;
else return 0;
}
//判断是否为闰年
public static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
}