【问题标题】:Set a date object in java from a string retaining the same format从保留相同格式的字符串中设置java中的日期对象
【发布时间】:2015-06-25 18:33:19
【问题描述】:

我有一个从数据库中读取数据的应用程序。数据库有一个日期列值以

格式存储
Sat Oct 19 10:03:00 EDT 2013

然后我使用日期列所在的 getter 和 setter 从我的 java 代码中读取数据库

node.setHeadTime(Date newDate)
node.getHeadTime();

因此它是一个日期对象,我将日期作为

Sat Oct 19 19:33:00 IST 2013

现在我做了一些处理,其中我需要更新数据并将其存储回数据库。

数据改成

Sat Oct 19 19:35:00 IST 2013

我需要将此数据存储回数据库

Sat Oct 19 10:05:00 EDT 2013

我尝试了以下代码:

DateFormat edtFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        TimeZone edt = TimeZone.getTimeZone("America/New_York");
        edtFormat.setTimeZone(edt);
        DateFormat df = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy"); // The timezone 'z' identifier was missing, I have added that now.
        Date dd1 = df.parse(headDate); //headdate is the date having string Sat Oct 19 19:35:00 IST 2013

String hd=edtFormat.format(dd1);
log.info("date "+hd);
        fnFillDetails(String hd);

这成功打印了 Sat Oct 19 10:05:00 EDT 2013。

但我的问题是 更改格式后,我将其发送到函数

fnFillDetails(String hd){

node.setheaddate(hd); // But this obviously has an error as type mismatch of Date and String. 
}

我尝试了所有可能的解决方法,但都没有奏效。我无法将 headdate 的数据类型更改为 String。

我该如何解决这个问题?我需要保留格式并将其更改回数据库中的原始格式。

【问题讨论】:

  • “数据库有一个以格式存储的日期列值” - 为什么该值不存储为作为日期值?这是哪个数据库?您确定您看到的不只是Date.toString() 的结果吗? (您需要区分调试时可能看到的任何文本,以及实际存储/检索数据的方式。)
  • 日期没有任何格式。既不是 Java 日期,也不是数据库日期。只需使用 ResultSet.getTimestamp() / PreparedStatement.setTimestamp(),无需尝试将日期转换为字符串。
  • 如果无法更改 headdate 的数据类型,则将 Date 传递给 fnFillDetails。
  • 没有日期列是文本类型。使用 Cassandra 数据库。是的,我确定。我的问题是我需要在这里设置 node.setheaddate(Date) //here。但我正确的结果是在一个字符串中。我想维护 String 的相同结果,但将其转换为 Date 对象
  • @faheemfarhan :如果我通过 Date 在我的情况下 dd1 :我在错误的时区得到结果。我只在 EDT 中需要它。

标签: java date cassandra simpledateformat


【解决方案1】:
        String headDate = "Sat Oct 19 19:35:00 IST 2013";

        DateFormat edtFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        TimeZone edt = TimeZone.getTimeZone("America/New_York");
        edtFormat.setTimeZone(edt);

        DateFormat istFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        TimeZone ist = TimeZone.getTimeZone("Asia/Kolkata");
        istFormat.setTimeZone(ist);

        Date dd1 = istFormat.parse(headDate);
        String hd=edtFormat.format(dd1);
        System.out.println(hd);

所以现在如果你想将 edt 格式传递给 fnFillDetails 然后调用

Date edtDate = edtFormat.parse(hd);
fnFillDetails(edtDate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多