public class dateTime { public static void main(String[] args) { showDateTime(); } public static void showDateTime() { int year = 1970; long totalSeconds = System.currentTimeMillis() / 1000; long currentSeconds = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinutes = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHours = (totalHours + 8) % 24; long totalDays = totalHours / 24; while (totalDays >= daysPerYear(year)) { // 必须是≥ totalDays -= daysPerYear(year); year++; } int monthNum = 1; while (totalDays >= daysPerMonth(monthNum, year)) { // 必须是≥ totalDays -= daysPerMonth(monthNum, year); monthNum++; } long currentDays = totalDays + 1; System.out.println("Current date and time is " + month(monthNum) + " " + currentDays + ", " + year + " " + currentHours + ":" + currentMinutes + ":" + currentSeconds); } public static int daysPerYear(int year) { if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) return 366; return 365; } public static int daysPerMonth(int month, int year) { return switch (month) { case 1, 3, 5, 7, 8, 10, 12 -> 31; case 4, 6, 9, 11 -> 30; case 2 -> daysPerYear(year) == 365 ? 28 : 29; default -> 0; }; } public static String month(int monthNum) { return switch (monthNum) { case 1 -> "January"; case 2 -> "February"; case 3 -> "March"; case 4 -> "April"; case 5 -> "May"; case 6 -> "June"; case 7 -> "July"; case 8 -> "August"; case 9 -> "September"; case 10 -> "October"; case 11 -> "November"; case 12 -> "December"; default -> "invalid number of month"; }; } }
Java语言程序设计第6章编程练习题6.33(当前日期和时间)调用System.currentTimeMillis()返回从1970年1月1日0点至今的毫秒数。编写程序,显示当前日期和时间。
于 2022-02-27 21:39:50 首次发布