java 将日历日期转换为 LocalDate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48983572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Calendar date to LocalDate
提问by Rod182211
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.
我决定从 5.5 升级到 Optaplanner 7.5 Nurseroster,但遇到了一些愚蠢的问题。下面是一个。我以前使用的例程如下。然而,现在新版本需要 LocalDate。我有一个 MySql 数据库后端,用户通过日历选择名册计划计划。任何建议将不胜感激。
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);
}
回答by Asad Shakeel
I have tried the following code to get the LocalDatefrom Calendar
我已尝试使用以下代码从日历中获取LocalDate
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
我已按照此链接将日历转换为 LocalDateTime 中的这些步骤
回答by dilanSachi
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 Datetype and then converts it to LocalDateformat as far as I know.
据我所知,这首先获取Date类型的日期,然后将其转换为LocalDate格式。