有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从保留相同格式的字符串中设置java中的日期对象

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

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);

这张照片于2013年10月19日美国东部夏令时10:05:00成功打印

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

fnFillDetails(String hd){

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

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

如何解决此问题?我需要保留格式,并在数据库中将其更改回原始格式


共 (1) 个答案

  1. # 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);