How do I control the formatting of dates in a URL with Play?
I have a Play application that should list out purchases within a give开发者_运维知识库n date interval. If the user does not give any date interval, it should default to showing purchases within the last year. This is done with these two methods in my controller:
public static void show(String id) {
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1);
Date oneYearAgo = calendar.getTime();
showWithInterval(id, oneYearAgo, today);
}
public static void showWithInterval(String id, Date fromDate, Date toDate) {
List<Purchase> purchases= Purchase.find(id, fromDate, toDate);
render(purchases, fromDate, toDate);
}
However, this produces a url looking like this: http://localhost:9000/purchases/showwithinterval/10076430719?fromDate=ISO8601:2010-01-17T19:41:20%2B0100&toDate=ISO8601:2011-01-17T19:41:20%2B0100
This does not adhere to the date format I have specified with the date.format
property in application.conf
. This format is simply not usable, as I want to be able to print the dates (using ${params.fromDate}
) and let my users edit them to show other intervals. I cannot format them in the view, since they are strings.
Does anyone know how to fix this?
Edit: Fixed a typo
Add fromDate et toDate to your render method :
render(purchases,fromDate,toDate);
and format them :
${fromDate.format()}
Play will format the date with your format configuration in application.conf
there are several ways to influence the format of date parametes in URLS.
play.data.binding.As Annotation
since Play 1.1 you can influence the route and data binding with this annotation. Simply add an @As annotation as follows to your date parameter:
public static void submit(@As("dd/MM/yyyy")Date myDate) { Logger.info("date %s", new SimpleDateFormat("dd-MM-yyyy").format(myDate)); }
more information about the annotation can be found here http://www.playframework.org/documentation/1.1/releasenotes-1.1
application.conf
take a look at the i18n/DateFormat section
精彩评论