Play Framework 2.1中视图的相对时间 [英] Relative time for views in Play Framework 2.1

查看:177
本文介绍了Play Framework 2.1中视图的相对时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Play框架使用(?)有一个,因为()函数来获取Play 1的视图中的相对时间(如4分钟前) 。X。这被称为日期扩展名此处

It seems like the Play Framework used(?) to have a since() function to get relative time (like "4 minutes ago") in views for Play 1.x. This is mentioned as a Date Extension here

然而,在Play 2.1中,这似乎不再起作用了。我得到值,因为它不是java.util.Date的成员 ...另外我找不到任何其他对的引用,因为()(在Play 2.1的上下文中)在线。

However in Play 2.1 this doesn't appear to work anymore. I get value since is not a member of java.util.Date ... Additionally I can't find any other references to since() (in the context of Play 2.1) online.

是否有正确/默认的方式来处理这种常见情况?我觉得我必须遗漏一些重要的东西,因为似乎不再受支持了吗?

Is there a proper/default way of handling this common case? I feel like I must be missing something important since this seems to no longer be supported?

谢谢!

推荐答案

@Jack提出了一个很好的答案。

@Jack suggested a pretty good answer.

这是他的代码的一个版本可能很有用,因为它会在需要时启用一些组合(检查功能不是作曲,但可以轻松改变以构图并显示更详细的值。)

Here is a version of his code that might be useful because it'll enable some composition if needed (the check function is not composing but could be easily changed to compose and show a more detailed since value)

package object pimps {

  import java.util.Date
  import org.joda.time.DateTime;
  import org.joda.time.Period;

  def step(f:Period => Int)(fi:String):Period => Option[String] = {
    def g(i:Int = 1) = i + " " + fi + (if (i==1) "" else "s") + " ago"

    (p:Period) => {
      f(p) match {
        case 0 => None
        case 1 => Some(g())
        case x => Some(g(x))
      }
    }
  }
  val yearsStep = step(_.getYears)("year")
  val monthsStep = step(_.getMonths)("month")
  val daysStep = step(_.getDays)("day")
  val hoursStep = step(_.getHours)("hour")
  val minutesStep = step(_.getMinutes)("minute")
  val secondsStep = step(_.getSeconds)("second")
  val steps = Seq(yearsStep, monthsStep, daysStep, hoursStep, minutesStep, secondsStep)

  val check = 
    (p:Period) =>
      steps.collectFirst {
        case f if f(p).isDefined => f(p).get
      }

  implicit class PimpedDate(col: Date) {

    def since() = {
      val period: Period = new Period(new DateTime(col), DateTime.now);
      check(period)
    }
  }
}

正如你所看到的,现在我们停在第一个匹配级别,我们也重复getter(getYears如果匹配将被调用两次)。

As you can see, for now we stop at the first matching level, and also we repeat the getter (getYears if matching will be called twice).

尽管如此,另一件需要注意的是使用隐式类,它已经在Scala 2.10中引入以缓解拉皮条

Nevertheless, another thing to note is the usage of implicit class which has been introduced in Scala 2.10 to ease the pimping

这篇关于Play Framework 2.1中视图的相对时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆