gpt4 book ai didi

java - 如何处理从 HTML 收集的日期并保存在 MongoDB 中

转载 作者:行者123 更新时间:2023-12-01 08:48:01 24 4
gpt4 key购买 nike

我试图处理从 HTML 表单收集的日期,简直要发疯了。我使用 Spring 4 作为后端,使用 Mongodb 作为持久性。

我的问题是 Mongo 中日期的显示方式。我想获得以下格式:dd-MM-yyyy。我想我明白 Mongo 默认使用 ISO 格式(yyyy-MM-dd'T'HH:mm:ssZ),但是当我尝试插入新文档时,填写表单后,日期将保存为数字值,所以我的问题是:

  1. 为什么会发生这种情况?
  2. 是否可以以 dd-MM-yyyy 格式保存日期,并保持 DateOfBirth 类型?
  3. 如果不是,如何以标准 ISO 格式保存日期?

客户类(我更改了setter方法,以便解析表单绑定(bind)的日期)

@Document
public class Customer implements UserDetails {
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private Date dateOfBirth;
private String username;
private String email;
private String password;
private String role;

public Customer() { }

public Customer(String firstName, String lastName, Date dateOfBirth, String username,
String email, String password, String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.username = username;
this.email = email;
this.password = password;
this.role = role;
}

//getters, setters, etc.

public Date getDateOfBirth() {
return this.dateOfBirth;
}

public void setDateOfBirth(String dateOfBirth) {
try {
this.dateOfBirth = new SimpleDateFormat("dd-MM-yyyy").parse(dateOfBirth);
}
catch (ParseException e) {
//...
}
}
}

注册.html

<div class="form">
<h2>Registration</h2>
<form th:action="@{/registration}" method="POST"
th:object="${customer}">
<input type="text" placeholder="Nome" name="firstName"
th:field="*{firstName}" /> <input type="text" placeholder="Cognome"
name="lastName" th:field="*{lastName}" /> <input type="date"
name="dateOfBirth" th:field="*{dateOfBirth}" /> <input type="text"
placeholder="Username" name="username" th:field="*{username}" /> <input
type="email" placeholder="Email" name="email" th:field="*{email}" />
<input type="password" placeholder="Password" name="password"
th:field="*{password}" />
<button type="submit">Submit</button>
</form>
</div>

使用“/registration”值映射的 Controller 使用 DAO 插入新客户。

这是结果:

MongoDB result

谢谢您的建议。

最佳答案

我认为没有问题,但您需要一些解释。

Why is this happening?

您看到的值仍然是一个日期,它只是在您正在使用的查看器中以长等效形式显示。

通过 Mongo shell 检查同一文档,您应该看到 ISO 格式的日期,但在内部它以长值保存。

Is possible to save the Date in dd-MM-yyyy format keeping dateOfBirth of Date type?

dd-MM-yyyy 是日期格式,如果你想存储它,你必须将日期类型更改为字符串。不推荐。

If it's not, how can I ave the Date in the standard ISO format?

您不以任何格式保存日期。它的内部表示是一个长整型值。第一点应该回答格式部分。

关于java - 如何处理从 HTML 收集的日期并保存在 MongoDB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com