问题
From what I can see in the auto-generated application.conf
file, dates/times in Play Framework 2.2 are formatted according to the definition of date.format
in that file. I have, for instance, defined
date.format=yyyy-MM-dd
date.format.dk=d. MMMM yyyy
These values, however, seem to be ignored by the framework when printing dates in Scala templates. This thread gives a solution where one enters the pattern directly into the template as myDate.format("yyyy-MM-dd")
. (If using Jodatime I guess this becomes myDate.toDate().format("yyyy-MM-dd")
since there is no format()
defined on the DateTime
class.) But not only does this force one to repeat the pattern each time a date is displayed, it also ignores the current locale.
So what is the intended way to format date and time in Play Framework 2.2.x with respect to different locales?
回答1:
In short, if you want to hard code the locale and use JodaTime:
@(date: org.joda.DateTime)
@import java.util.Locale
@date.format("yyyy-MMM-dd", new Locale("sv", "SE"))
if you want to use the locale selected from the browser lang header (you will also need the request implicitly to your template):
@(date: org.joda.DateTime)(implicit lang: play.api.i18n.Lang)
@date.format("yyyy-MMM-dd", lang.toLocale)
I wrote a detailed blog entry about this (since I have seen the question so many times):
https://markatta.com/codemonkey/blog/2013/10/14/formatted-localized-dates-in-playframework-2/
回答2:
I found this here Google group (I own no credit for this but I thought it could help somebody)
@(myDate: org.joda.time.DateTime)
@import org.joda.time.format.DateTimeFormat
@defining(DateTimeFormat.forPattern("yyyy-MM-dd")) { dateFormatter =>
@dateFormatter.print(myDate) )
}
alternatively you can have this
val dateFormatter = org.joda.time.format.DateTimeFormat.forPattern(myDatePattern)
and call it in the template as (assuming it is stored in utils and Object Format):
@utils.Format.dateFormatter.print(myDate)
works very well for me
来源:https://stackoverflow.com/questions/19335705/date-formatting-with-locale-in-play-framework-2-2