Java语言程序设计第6章编程练习题6.33(当前日期和时间)调用System.currentTimeMillis()返回从1970年1月1日0点至今的毫秒数。编写程序,显示当前日期和时间。

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";
        };
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋凉78

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值