我正在試圖處理從HTML表單收集的日期。我將Spring 4用於後端,Mongodb用於持久性。如何處理從HTML中收集的日期和保存在MongoDB中的日期
我的問題是如何在Mongo中顯示日期。我想要得到以下格式:dd-MM-yyyy。我想我明白Mongo使用ISO格式作爲默認值(yyyy-MM-dd'T'HH:mm:ssZ),但是當我嘗試插入新文檔時,在填寫表單後,日期被保存爲一個數字價值,所以我的問題是:
- 這是爲什麼發生?
- 是否可以將日期保存爲dd-MM-yyyy格式,並保留dateOfBirth類型的日期?
- 如果不是,我該如何使用標準ISO格式的日期?
Customer類
@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) {
//...
}
}
}
registration.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>
的控制器,該控制器(I爲了解析由形式綁定日期改變setter方法)與「/ registration」值映射使用DAO插入新的Customer。
這是結果:
謝謝你的建議。
感謝您清除我的疑惑! – andy
我試圖將保存在數據庫中的日期值顯示到視圖中,並且日,月和年不匹配。例如,如果我插入19 06 1990,則顯示的值爲Fri Nov 10 00:00:00 CET 24.我錯在哪裏? – andy
我不確定它出錯的地方。首先,你看到db中的正確值嗎? – Veeram