2016-05-13 55 views
1

我試圖格式化Grails的一個Date日期格式,這裏是我的控制器代碼:輸出錯誤的Grails中

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); 
empRefInstance.startDate=sdf.parse(params.startDate) 
empRefInstance.endDate=sdf.parse(params.endDate) 
println ("dates " + empRefInstance.startDate +" "+empRefInstance.endDate) 

應該是01-05-2016按照我定義的格式,但輸出這兩種日期格式的輸出

Sun May 01 00:00:00 EEST 2016 

formater有什麼問題嗎?

+0

你是如何得到該輸出?你沒有在你的問題中包括這個。 –

+0

@JoshuaMoore我編輯了問題 – Sherif

+0

假設'startDate'和'endDate'都是'Date'數據類型嗎?如果是這樣的話,那麼這是預期的默認行爲,以便在未格式化時輸出「日期」。如果你想以特定格式顯示,你可以使用'.format()'方法。像這樣:'empRefInstance.startDate.format('dd-MM-yyyy')' –

回答

0

您不是格式化輸出,而是隻解析。

格式化:轉換的DateString(該format法)
解析:轉換的StringDate(該parse法)

格式化,你需要做的像這個:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); 
// First you are converting the incoming date string to a date 
empRefInstance.startDate = sdf.parse(params.startDate) 
empRefInstance.endDate=sdf.parse(params.endDate) 

// Now we have to conert the date object to string and print it 
println ("dates " + sdf.format(empRefInstance.startDate) + " "+sdf.format(empRefInstance.endDate)) 

當您打印在Groovy/Java的一個Date對象,它是toString()默認的實現將被調用,因此你喜歡Sun May 01 00:00:00 EEST 2016

也越來越輸出,Groovy中增加了在Dateformat方法直接允許格式。你甚至可以使用它。

println("dates " + empRefInstance.startDate.format("dd-MM-yyyy") + " " + empRefInstance.endDate.format("dd-MM-yyyy")) 
0

格式化程序沒有任何問題。你沒有使用輸出。這樣的事情會給你預期的輸出:

println empRefInstance.startDate.format('dd-MM-yyyy')

+0

當我嘗試'empRefInstance.startDate = sdf.format(sdf.parse(params.startDate))''我'無法投射物體'01 -05-2016'與班級'java.lang.String'到班'java.util.Date'' – Sherif

+0

這是因爲你正在試圖設置一個'日期'爲'String'的值。這是毫無意義的。你想通過這樣做完成什麼?你的問題是關於如何得到一個日期格式輸出正確,但你的評論是處理設置(輸入)。 –

+0

我想要做的是我得到日期startDate和endDate在我的域名,並從視圖中返回這些字段是字符串,所以我想將字符串轉換爲日期並將其設置爲'empRefInstance.starDate'與格式'dd-MM-yyyy' – Sherif