[英]Set a date object in java from a string retaining the same format
我有一個從數據庫讀取數據的應用程序。 數據庫具有以格式存儲的日期列值
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 EDT。
但我的問題是在我更改格式后,我將其發送給一個函數
fnFillDetails(String hd){
node.setheaddate(hd); // But this obviously has an error as type mismatch of Date and String.
}
我嘗試了所有可能的解決方法都沒有奏效。 我無法將 headdate 的數據類型更改為 String。
我該如何解決這個問題? 我需要保留格式並將其改回數據庫中的原始格式。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.