从日期选择器中获取价值 [英] Get value from Date picker

查看:118
本文介绍了从日期选择器中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从JavaFX datepicker获取值并将值存储为Date Object:

I want to get the value from JavaFX datepicker and store the value as Date Object:

final DatePicker datePicker = new DatePicker(LocalDate.now());
Date date = datePicker.getValue();
grid.add(datePicker, 1, 9);

你能告诉我如何转换 LocalDate 日期

Can you tell me how I can convert LocalDate to Date?

推荐答案

顾名思义,LocalDate不会存储时区或一天中的时间。因此,要转换为绝对时间,您必须指定时区和时间。有两种方法可以做到这一点,atStartOfDay(ZoneId)。这里我使用默认时区,它是计算机的本地时区。这为您提供了一个Instant对象,它代表并及时。最后,Java 8在Date中添加了一个工厂方法来构建一个Instant。

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);

这将为您提供如下输出。请注意,Instant默认以UTC格式打印。

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

当然,你会需要将java.util.Date转换为java.time.LocalDate以设置DatePicker上的值。为此你需要这样的东西:

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

这篇关于从日期选择器中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆