将 HTML 日期输入解析为 Java Servlet

问题描述

最近我遇到了时间戳和 HTML 输入类型日期的问题:

这是我的 HTML/JSP:

<div class="form-group">
   <label>Your day of birth</label>
   <input class="form-control form-control-lg" type="date" name="txtBirthdate" required="">
</div>

这是我的 Java Servlet:

String birth = request.getParameter(Constants.BIRTHDATE_TXT);
System.out.println(birth);
Timestamp bDate = new Timestamp(((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(birth)).getTime()));
System.out.println(bDate);
Timestamp joinDate = new Timestamp(Calendar.getInstance().getTime().getTime());

我无法将出生的字符串解析为时间戳,有什么方法可以转换它吗?当您使用 SimpleDateFormat 去除 yyyy-MM-dd 字符串时,我是否正确,它会将 HH:mm:ss 部分设置为认值为 00:00:0000?

感谢您的帮助

解决方法

java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。请注意,java.sql.Timestamp 继承了与扩展 java.util.Date 相同的缺点。建议完全停止使用它们并切换到 modern date-time API。出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。如果您正在工作对于 Android 项目并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

你提到过,

我的问题是我真的不知道如何解析日期,例如: “2020-12-28”进入时间戳

你也提到了,

当您使用 SimpleDateFormat,它将设置 HH:mm:ss 部分,默认值为 00:00:0000?

根据这两个要求,我推断您需要一个日期,例如2020-12-28 结合时间,例如00:00:00 只是一天的开始。 java.time 提供了一个干净的 API,LocalDate#atStartOfDay 来实现这一点。

演示:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDate = "2020-12-28";

        // Parse the given date string into LocalDate. Note that you do not need a
        // DateTimeFormatter to parse it as it is already in ISO 8601 format
        LocalDate date = LocalDate.parse(strDate);

        // Note: In the following line,replace ZoneId.systemDefault() with the required
        // Zone ID which specified in the format,Continent/City e.g.
        // ZoneId.of("Europe/London")
        ZonedDateTime zdt = date.atStartOfDay(ZoneId.systemDefault());

        // Print the default format i.e. the value of zdt#toString. Note that the
        // default format omits seconds and next smaller units if seconds part is zero
        System.out.println(zdt);

        // Get and print just the date-time without timezone information
        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);

        // Get and print zdt in a custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS",Locale.ENGLISH);
        String formatted = zdt.format(dtf);
        System.out.println(formatted);
    }
}

输出:

2020-12-28T00:00Z[Europe/London]
2020-12-28T00:00
2020-12-28T00:00:00.000

Trail: Date Time 了解现代日期时间 API。