我可以以某种方式设置日期的格式,类似于g:formatDate标签如何执行此操作,但是在Service中?包括i18n和l10n?g:formatDate服务中的替代
它可能不是在服务做到这一点的最佳做法,因为这应该是观点的逻辑更容易一部分,但我需要返回一个日期作为JSON响应的一部分,我不想在JS中处理这个问题(主要是因为l10n)。
感谢您的咨询。
我可以以某种方式设置日期的格式,类似于g:formatDate标签如何执行此操作,但是在Service中?包括i18n和l10n?g:formatDate服务中的替代
它可能不是在服务做到这一点的最佳做法,因为这应该是观点的逻辑更容易一部分,但我需要返回一个日期作为JSON响应的一部分,我不想在JS中处理这个问题(主要是因为l10n)。
感谢您的咨询。
这里有几个选项,不涉及从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
还有其他选项,如上所述格式化控制器中的日期就是其中之一。 – chim 2017-01-26 11:31:06
您可以在服务或控制器一样,使用formatDate:
g.formatDate(date: new Date(), type: "date", style:"MEDIUM")
您可以用同样的方法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
可能使用控制器中的g。*标记。然而,AFAIK taglibs不能用于服务 - 这是我现在需要的更多东西(我将从问题中删除控制器)。无论如何感谢 – pseudo 2013-03-15 17:59:07
看看这篇文章访问服务中的g,如果你真的想使用formatDate http://stackoverflow.com/questions/1777640/using-g-render-in-a-grails-service – Alidad 2013-03-15 18:03:34