Get value from Date picker

喜夏-厌秋 提交于 2019-11-30 09:37:41

As the name implies, LocalDate does not store a timezone nor the time of day. Therefore to convert to an absolute time you must specify the timezone and time of day. There is a simple method to do both, atStartOfDay(ZoneId). Here I use the default time zone which is the local timezone of the computer. This gives you an Instant object which represents and instant in time. Finally, Java 8 added a factory method to Date to construct from an Instant.

LocalDate localDate = datePicker.getValue();
Instant instant = Instant.from(localDate.atStartOfDay(ZoneId.systemDefault()));
Date date = Date.from(instant);
System.out.println(localDate + "\n" + instant + "\n" + date);

This will give you an output like below. Note that the Instant by default prints in UTC.

2014-02-25
2014-02-25T06:00:00Z
Tue Feb 25 00:00:00 CST 2014

Of course, you will need to convert your java.util.Date into a java.time.LocalDate to set the value on the DatePicker. For that you will need something like this:

Date date = new Date();
Instant instant = date.toInstant();
LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date + "\n" + instant + "\n" + localDate);

Which will give you output like:

Tue Feb 25 08:47:04 CST 2014
2014-02-25T14:47:04.395Z
2014-02-25
Dmitry Nelepov

Or you can use more simplest way

java.sql.Date gettedDatePickerDate = java.sql.Date.valueOf(myDatePicker.getValue());

And then you can perform operation within this date object.

Convert to java.util.Date

Converting java.sql.Date to java.util.Date

I don't have IDE at hand but this should do the trick.

Date date = new Date(datePicker.getvalue().toEpochDay());

Or alternatively.

LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue(), ld.getDayOfMonth());
Date date = c.getTime();

LeonidasCZ answer is not 100% correct: java.util.Date months range is from 0 to 11, but Calendar.getInstance() is from 1 to 12, so you can do this:

LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue() - 1, ld.getDayOfMonth());
Date date = c.getTime();

If you want to add hours, mins, seconds too:

LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue() - 1, ld.getDayOfMonth(), hours, minutes, seconds);
Date date = c.getTime();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!