gpt4 book ai didi

java - Hibernate 处理日期和时间 - PostgreSql

转载 作者:行者123 更新时间:2023-11-29 12:58:36 25 4
gpt4 key购买 nike

我在那个实体中有一个实体我有 2 个属性:
dateStart - 应该只包含 yyyy-MM-dd
timeStart - 应该只包含时间 HH:mm

我正在使用 postgreSQL 数据库。我的表是这样定义的:

CREATE TABLE xxx
(
dateStart date,
timeStart time without time zone
)

我像这样使用 hibernate 在 java 中映射了这个表(日期是 java.util.Date 的类型,如果可能的话我想坚持使用它):

@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateStart;

@Temporal(TemporalType.TIME)
@DateTimeFormat(pattern = "HH:mm")
private Date dateTime;

我也在用 Spring 。我有一个表单,用户可以在其中填写实际创建该实体的输入

<form:form method="post" class="form-horizontal" action="..." commandName="xxx">
<form:input path="dateStart" type="date"/>
<form:input path="timeStart" type="time"/>
.....
<submit button>
</form:form>

这是我实际创建实体的 Controller (当用户提交表单时)

@RequestMapping(value = "/viewSpecificTests", method = RequestMethod.POST)
public String viewSpecificTests(Model model, @Valid XXX xxx, BindingResult result) {

if (result.hasErrors()) {
return "createSpecificTest";
}

xxxService.createTable(xxx);
return "viewSpecificTests";
}

然而,当我打印我的实体 xxx.toString() 时。我的日期和时间没有正确存储。dateStart 看起来像这样:2016 年 CEST 4 月 5 日星期二 00:00:00
日期时间看起来像这样:Thu Jan 01 12:30:00 CET 1970

如何告诉 hibernate 只保留日期/时间?由于某种原因,@Temporal 无法按照我想要的方式为我工作,我被这个问题困扰了很长时间。

最佳答案

我认为您应该将日期存储为日期。然后,当您从数据库中检索日期对象时,请使用我所说明的简单日期格式。

  public void getDate(){
Date d = new Date();//Put your date here

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");//use java.text.SimpleDateformat

String newFomart = formatter.format(d);
}

这将以您想要的格式返回字符串。正如我所展示的,你必须做的就是通过你的约会。记住还要在 new SimpleDateFormat("String"); 中设置你想要的格式;

关于java - Hibernate 处理日期和时间 - PostgreSql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36421537/

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