Convert Calendar date to LocalDate

不问归期 提交于 2019-12-10 18:45:49

问题


I decided to upgrade from 5.5 to Optaplanner 7.5 Nurseroster but have run into a number of silly issues. Below is one. The routine I previously used is below. Now however the new version requires LocalDate. I have an MySql database back-end and the users select the roster schedule planner via a calendar. Any suggestions will be appreciated.

int shiftDateSize = maxDayIndex + 1;
        List<ShiftDate> shiftDateList = new ArrayList<ShiftDate>(shiftDateSize);
        //shiftDateMap = new HashMap<String, ShiftDate>(shiftDateSize);
        long id = 0L;
        int dayIndex = 0;
        calendar.setTime(startDate);
        for (int i = 0; i < shiftDateSize; i++) {
            ShiftDate shiftDate = new ShiftDate();
            shiftDate.setId(id);
            shiftDate.setDayIndex(dayIndex);
            **String dateString = dateFormat.format(calendar.getTime());**
            shiftDate.setDateString(dateString);
            **shiftDate.setDayOfWeek(DayOfWeek.valueOfCalendar(calendar.get(Calendar.DAY_OF_WEEK)));**
            shiftDate.setShiftList(new ArrayList<Shift>());
            shiftDateList.add(shiftDate);
            shiftDateMap.put(dateString, shiftDate);
            id++;
            dayIndex++;
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        nurseRoster.setShiftDateList(shiftDateList);
    } 

回答1:


I have tried the following code to get the LocalDate from Calendar

Calendar calendar = Calendar.getInstance();
TimeZone tz = calendar.getTimeZone();
ZoneId zid = tz == null ? ZoneId.systemDefault() : tz.toZoneId();
LocalDate localDate = LocalDateTime.ofInstant(calendar.toInstant(), zid).LocalDate();

or simply in one line:

LocalDate localDate = LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()).toLocalDate();

I have followed these steps from this link Convert Calendar to LocalDateTime




回答2:


The following code probably works too.

Calender cal = Calender.getInstance();
Date input = cal.getTime();
LocalDate da = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

This first gets the date in Date type and then converts it to LocalDate format as far as I know.



来源:https://stackoverflow.com/questions/48983572/convert-calendar-date-to-localdate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!