<tr class="rowsAdded">
<td><input name="item" class="form-control" type="text" placeholder="Item" /></td>
<td><input name="amount" class="form-control" type="number" placeholder="Amount" /></td>
<td><input name="expenseDate" class="form-control" type="date"placeholder="ExpenseDate" /></td>
</tr>
以下是我的控制器和Init Binder
@RequestMapping (value = "/saveExpenses", method=RequestMethod.POST)
public String saveExpenses (@RequestBody ExpenseDetailsListVO expenseDetailsListVO, Model model,BindingResult result) {
if (result.hasErrors()) {
System.out.println(result.getFieldError().getField().toString()+" error");
}
System.out.println(expenseDetailsListVO);
return "success";
}
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
这样我想要的日期格式不起作用,这是我得到的输出 expenseDate = Wed Mar 18 05:30:00 IST 2015 但是我想把它变成像yyyy-MM-dd这样的特定格式......建议我这样做。
答案 0 :(得分:8)
这不会更容易吗?
实体或表单备份对象:
class Foo {
/* handles data-binding (parsing) and display if spring form tld or spring:eval */
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date expenseDate;
...
}
表格形式:
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<form:form modelAttribute="modelAttributeName">
<form:input type="date" path="expenseDate" />
</form:form>
或者只是显示:
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<spring:eval expression="modelAttributeName.expenseDate" />
一些迂腐的笔记:
请在此处查看我的帖子,了解最佳做法:Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security
答案 1 :(得分:6)
我不知道这个答案对你有帮助吗? 我的实体类之一如下......
@Entity
@Table(name = "TAIMS_INC_INCIDENT")
public class Incident implements Serializable{
@DateTimeFormat(pattern = "dd/MM/yyyy") // This is for bind Date with @ModelAttribute
@Temporal(TemporalType.DATE)
@Column(name = "inc_date")
private Date incidentDate;
}
<input type="text" id="incident-date" name="incidentDate" value="23/08/2017" />
Spring Controller Method Here ..
@RequestMapping(value = "/saveIncident.ibbl", method = RequestMethod.POST)
public ModelAndView saveIncident(
@ModelAttribute("incident")
Incident incident,
BindingResult result){
System.out.println(incident.getIncidentDate());
// Wed Aug 23 00:00:00 BDT 2017
}
这很好用。 Incident incident
包含eventsDate = Wed Aug 23 00:00:00 BDT 2017
如果您不想在Entity类中使用 @DateTimeFormat(pattern = "dd/MM/yyyy")
,请将以下方法放在Controller Class中...
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
答案 2 :(得分:0)
我所说的是你的活页夹可能效果很好。它的作用是从HTTP请求的主体中获取格式为yyyy-MM-dd的String,并将其转换为Date对象。但这就是它的全部。在此之后您使用该Date对象做什么由您决定。如果你想把它作为一个String传递给程序的其他部分你应该转换它,也许使用SimpleDateFormatter。