Date formatting with language version in Play Framework 2.2

From what I see in the auto-generated file application.conf, the dates / times in the Play Framework 2.2 are formatted as defined date.formatin this file. For example, I defined

date.format=yyyy-MM-dd
date.format.dk=d. MMMM yyyy

These values, however, are apparently ignored by the framework when printing dates in Scala templates. This thread provides a solution in which you get into the template directly into the template as myDate.format("yyyy-MM-dd"). (If you use Jodatime, I think it becomes myDate.toDate().format("yyyy-MM-dd")because it is DateTimenot in the class format().) But it not only forces the template to be repeated every time the date is displayed, but also ignores the current locale.

So, what is the intended way to format date and time in Play Framework 2.2.x for different locales?

+4
source share
2 answers

In short, if you want to hardcode the language 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 a 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 saw the question many times):

https://markatta.com/codemonkey/blog/2013/10/14/formatted-localized-dates-in-playframework-2/

+7
source

Google ( , , -)

@(myDate: org.joda.time.DateTime)

@import org.joda.time.format.DateTimeFormat

@defining(DateTimeFormat.forPattern("yyyy-MM-dd")) { dateFormatter =>
    @dateFormatter.print(myDate) )
}

val dateFormatter = org.joda.time.format.DateTimeFormat.forPattern(myDatePattern)

( utils Object Format):

@utils.Format.dateFormatter.print(myDate)

+1

All Articles