大一新生第一次寫java程式,用System.currentTimeMillis() 獲取當前時間

Xu朝旭發表於2015-08-11

大一新生,看到相關書籍有這道題,要用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);
  }
}

相關文章