Convert java.util.Date to java.time.LocalDate

前端 未结 13 2414
温柔的废话
温柔的废话 2020-11-22 08:45

What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate?

Date input = new Date();
Loca         


        
13条回答
  •  隐瞒了意图╮
    2020-11-22 09:41

    public static LocalDate Date2LocalDate(Date date) {
            return LocalDate.parse(date.toString(), DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"))
    

    this format is from Date#tostring

        public String toString() {
            // "EEE MMM dd HH:mm:ss zzz yyyy";
            BaseCalendar.Date date = normalize();
            StringBuilder sb = new StringBuilder(28);
            int index = date.getDayOfWeek();
            if (index == BaseCalendar.SUNDAY) {
                index = 8;
            }
            convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
            convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
            CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
    
            CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
            CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
            CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
            TimeZone zi = date.getZone();
            if (zi != null) {
                sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
            } else {
                sb.append("GMT");
            }
            sb.append(' ').append(date.getYear());  // yyyy
            return sb.toString();
        }
    

提交回复
热议问题