Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date formatting with locale in Play Framework 2.2

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?

like image 752
plade Avatar asked Feb 16 '23 00:02

plade


1 Answers

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/

like image 137
johanandren Avatar answered Feb 21 '23 19:02

johanandren