在javaservlet中将html日期输入解析为时间戳

iovurdzv  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(272)

最近我遇到了时间戳和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());

我无法将字符串birth解析为时间戳,有什么方法可以转换它吗?我说的对吗?当你用simpledateformat裁剪yyyy-mm-dd字符串时,它会设置hh:mm:ss部分,默认值是00:00:0000?
谢谢你的帮助

8nuwlpux

8nuwlpux1#

api的日期时间 java.util 以及它们的格式化api, SimpleDateFormat 过时且容易出错。请注意 java.sql.Timestamp 继承了与扩展时相同的缺点 java.util.Date . 建议完全停止使用它们,并切换到现代日期时间api。出于任何原因,如果您必须坚持使用Java6或Java7,您可以使用threeten backport,它将大部分java.time功能向后移植到Java6和Java7。如果您正在为一个android项目工作,并且您的android api级别仍然不符合java-8,请检查通过desugaring提供的java8+api以及如何在android项目中使用threetenabp。
你提到过,
我的问题是我真的不知道如何将日期解析成时间戳,比如:“2020-12-28”
你还提到,
我说的对吗?当你用simpledateformat裁剪yyyy-mm-dd字符串时,它会设置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。

相关问题