How do I control the formatting of dates in a URL with Play?

放肆的年华 提交于 2019-12-24 02:58:09

问题


I have a Play application that should list out purchases within a given 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


回答1:


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




回答2:


there are several ways to influence the format of date parametes in URLS.

  1. 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

  2. application.conf
    take a look at the i18n/DateFormat section



来源:https://stackoverflow.com/questions/4716763/how-do-i-control-the-formatting-of-dates-in-a-url-with-play

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!