java中textfield参数类型,Java使用不同的格式从TextField中解析日期

I'm facing some problems in Eclipse with dates. I'm showing a date in a TextField with the format

dd/MM/yyyy

and I need to get the text from this textfield and parse it as a date to insert it in my database into a column of type DATE I'm using MySQL and it accepts dates as

yyyy-MM-dd

I tried really many options, both with LocalDate or the older Date, but didn't find a solution. Can someone please help? Thank you!

解决方案

Prior Java 8 approach

Firstly, after retrieving your string from your TextField, you should parse it to java.util.Date:

String text = textField.getText();

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

java.util.Date textFieldAsDate = null;

try {

textFieldAsDate = sdf.parse(text);

} catch (ParseException pe) {

// deal with ParseException

}

Afterwards, you can convert your java.util.Date into a java.sql.Date, to store it into your MySQL database, like this:

sdf = new SimpleDateFormat("yyyy-MM-dd");

java.sql.Date date = java.sql.Date.valueOf(sdf.format(textFieldAsDate));

Java 8 approach

As mentioned by @BasilBourque, the Java date and time mechanism was provided by java.util.Date, java.util.Calendar, and java.util.TimeZone classes which are now legacy.

Therefore, in order to accomplish using Java 8 what was previously mentioned, one can do the following:

String text = textField.getText();

java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd/MM/yyyy");

java.time.LocalDate textFieldAsDate = java.time.LocalDate.parse(text, formatter);

Afterwards, in order to convert the LocalDate into a java.sql.Date, to store it into your MySQL database, it's possible to do the following:

java.sql.Date sqlDate = java.sql.Date.valueOf(textFieldAsDate);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值