Chapter VI Question 24 (Display current date and time)

Chapter VI Question 24 (Display current date and time)

  • **6.24 (Display the current date and time) Listing 2-7 shows the current time. Improve this example to display the current date and time. The calendar example in Listing 6-12 can provide some ideas on how to find the year, month, and day.
    **6.24(Display current date and time) Listing 2.7, ShowCurrentTime.java, displays the current time. Revise this example to display the current date and time. The calendar example in Listing 6.12, PrintCalendar.java, should give you some ideas on how to find the year, month, and day.
  • Reference Code:
package chapter06;

public class Code_24 {
    
    
    public static void main(String[] args) {
    
    
        long totalMilliseconds = System.currentTimeMillis();
        int totalDays = (int) (totalMilliseconds / 1000 / 60 / 60 / 24);
        long totalSeconds = totalMilliseconds / 1000;
        long currentSecond = totalSeconds % 60;
        long totalMinutes = totalSeconds / 60;
        long currentMinute = totalMinutes % 60;
        long totalHours = totalMinutes / 60;
        long currentHour = totalHours % 24;
        int currentYears = 1970, currentMonths = 1, currentDays;
        while (totalDays >= 365) {
    
    
            if (isLeapYear(currentYears))
                totalDays -= 366;
            else
                totalDays -= 365;
            currentYears++;
        }
        while (totalDays >= 28) {
    
    
            if (currentMonths == 1 || currentMonths == 3 || currentMonths == 5 || currentMonths == 7 || currentMonths == 8 || currentMonths == 10 || currentMonths == 12) {
    
    
                totalDays -= 31;
                currentMonths++;
            }
            else if (currentMonths == 4 || currentMonths == 6 || currentMonths == 9 || currentMonths == 11) {
    
    
                totalDays -= 30;
                currentMonths++;
            }
            else if (isLeapYear(currentYears) && currentMonths == 2) {
    
    
                totalDays -= 29;
                currentMonths++;
            }
            else {
    
    
                totalDays -= 28;
                currentMonths++;
            }
        }
        if (totalDays == 0)
            currentDays = 1;
        else
            currentDays = totalDays + 1;
        System.out.printf("Current data is %d-%d-%d\n", currentYears, currentMonths, currentDays);
        System.out.printf("Current time is %d:%d:%d\n", currentHour, currentMinute, currentSecond);
    }
    public static boolean isLeapYear(int year) {
    
    
        return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
    }
}

  • The results show that:
Current data is 2020-10-19
Current time is 13:17:16

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109169305