2013-03-15 52 views
3

我可以以某種方式設置日期的格式,類似於g:formatDate標籤如何執行此操作,但是在Service中?包括i18n和l10n?g:formatDate服務中的替代

它可能不是在服務做到這一點的最佳做法,因爲這應該是觀點的邏輯更容易一部分,但我需要返回一個日期作爲JSON響應的一部分,我不想在JS中處理這個問題(主要是因爲l10n)。

感謝您的諮詢。

+0

您可以用同樣的方法formatDate從,如果你的控制器將。這是解釋它的帖子。 [這裏](https://stackoverflow.com/questions/7095086/grails-date-format-in-english-language)另外,如果你從服務中需要它,你仍然可以使用[here]解釋的方法訪問g(https) ://stackoverflow.com/questions/1777640/using-g-render-in-a-grails-service) – Alidad 2013-03-15 17:54:30

+0

可能使用控制器中的g。*標記。然而,AFAIK taglibs不能用於服務 - 這是我現在需要的更多東西(我將從問題中刪除控制器)。無論如何感謝 – pseudo 2013-03-15 17:59:07

+0

看看這篇文章訪問服務中的g,如果你真的想使用formatDate http://stackoverflow.com/questions/1777640/using-g-render-in-a-grails-service – Alidad 2013-03-15 18:03:34

回答

0

這裏有幾個選項,不涉及從grails應用程序中提取tagLib bean。

選項1: 如果你不是太擔心國際化 格式使用默認的常規方法,在服務的日期。

static final String DATE_FORMAT = 'dd-MM-yyyy' 
// ... 
Date date = new Date() 
String formattedDate = date.format(DATE_FORMAT) 

(這是你所需要的,沒有多餘的進口)

選項2: 如果你擔心國際化,但還是要格式化服務的日期,那麼你就可以得到默認日期格式

但首先你需要獲得語言環境中的服務,(這是警鐘應該開始振鈴)

// Don't do this... 
import org.springframework.context.i18n.LocaleContextHolder; 
// ... 
String locale = LocaleContextHolder.getLocale() 
// Don't do that ^^^ 

這將獲取與當前線程(如果有)或系統默認Locale其他相關的語言環境。但我們希望來自請求或會話的用戶的語言環境。

(那些警鐘應該由紅色閃燈現在可以加入),但是如果你想做到這一點,然後傳中,從通過方法調用控制器的請求。

然後你可以使用

import org.springframework.web.servlet.support.RequestContextUtils 
// ... 
def locale = RequestContextUtils.getLocale(request) 

所以我們有語言環境,現在我們可以得到的消息

// include the grailsApplication bean in the service 
def grailsApplication 
// ... 

// Get the date format 
def dateFormat = grailsApplication.mainContext.getMessage('default.date.format', null, 'dd-MM-yyyy', locale) 

// Then you can use the groovy default method 
String formattedDate = date.format(dateFormat) 

不要使用一個靜態方法來獲得該服務的請求。如果你這樣做,警報鈴聲和閃爍的紅燈將與你所在建築物的劇烈震動相連,只需從控制器中傳入即可。

方案3: 格式視圖

<g:set var="formattedDate" value="${g.formatDate(date: date)}" /> 

日這無疑是最乾淨的方法,但有時你不使用模板來歸還輸出。

選項4:

在服務獲取數據後使用一個標籤庫和輸出從控制器。 例如

def model = service.getModel() 
def output = myTagLib.myOutputHtmlMethod(model) 

然後你可以使用g.formatDate在myTagLib

+0

還有其他選項,如上所述格式化控制器中的日期就是其中之一。 – chim 2017-01-26 11:31:06

0

您可以在服務或控制器一樣,使用formatDate:

g.formatDate(date: new Date(), type: "date", style:"MEDIUM")