编程语言
首页 > 编程语言> > 看 java.util.Date 有感

看 java.util.Date 有感

作者:互联网

java8的日期时间工具很好用, 但性能最高的肯定是java.util.Date
其实sql包里的Date , Time , TimeStamp也挺好用
Calendar也还行
只是觉得 , 有时只是想获得 2021-04-02 这么简单的字符串, 需要经过那么复杂的代码和运算吗?
最基本的System.currentTimeMillis() 取自系统时间, 时区以操作系统为准
可否通过这么个long值简单解析出来,不需要时区,写出最精简的代码? 于是开始分析Date类
Date也不是简单一个类,设计好几个类,头晕晕~

设置年份要减去 1900

源码如此:

    /**
     * Allocates a {@code Date} object and initializes it so that
     * it represents the instant at the start of the second specified
     * by the {@code year}, {@code month}, {@code date},
     * {@code hrs}, {@code min}, and {@code sec} arguments,
     * in the local time zone.
     *
     * @param   year    the year minus 1900.
     * @param   month   the month between 0-11.
     * @param   date    the day of the month between 1-31.
     * @param   hrs     the hours between 0-23.
     * @param   min     the minutes between 0-59.
     * @param   sec     the seconds between 0-59.
     * @see     java.util.Calendar
     * @deprecated As of JDK version 1.1,
     * replaced by {@code Calendar.set(year + 1900, month, date, hrs, min, sec)}
     * or {@code GregorianCalendar(year + 1900, month, date, hrs, min, sec)}.
     */
    @Deprecated
    public Date(int year, int month, int date, int hrs, int min, int sec) {
        int y = year + 1900;
        // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
        if (month >= 12) {
            y += month / 12;
            month %= 12;
        } else if (month < 0) {
            y += CalendarUtils.floorDivide(month, 12);
            month = CalendarUtils.mod(month, 12);
        }
        BaseCalendar cal = getCalendarSystem(y);
        cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
        cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
        getTimeImpl();
        cdate = null;
    }

我猜是当年这么写是因为可以只写两位数 , 现在却是坑, 哈哈哈, 当时编程的人员并没想用到2000年以后呀

标签:code,java,int,hrs,month,util,year,Date
来源: https://blog.csdn.net/kfepiza/article/details/115409698