在Java Servlet中将HTML日期输入解析为时间戳



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

这是我的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相同的缺点。建议完全停止使用它们,并切换到现代日期时间API。无论出于何种原因,如果您必须坚持使用Java 6或Java 7,您可以使用ThreeTen BackportJava.time的大部分功能向后移植到Java 6&7.如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,请检查通过desugaring和如何在Android项目中使用ThreeTenABP提供的Java 8+API。

你提到过,

我的问题是我真的不知道如何解析日期,比如:"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

跟踪:日期时间了解现代日期时间API。

最新更新