【问题标题】:Grails time duration formatting tag libraryGrails 持续时间格式化标签库
【发布时间】:2015-05-21 18:46:57
【问题描述】:

Grails 有 3 个干净的格式化标签库:

  • 格式日期
  • 格式编号
  • 布尔格式

想知道是否有将秒格式化为 HH:MM:SS 的方法?或者是否有另一种优雅的方式来格式化渲染视图中的秒数。

注意:

formatDate 不起作用,因为秒数可能比86400 多。 所以在86461formatDate 的持续时间内将返回一个00:01:01,实际上它应该是24:01:01

【问题讨论】:

  • Grails 中没有内置的标签库可以这样做。但是,有很多 Java 库可以处理显示时间和持续时间,您可以使用它们来实现自己的标签库。
  • % 86400 那么也许?我希望公元 0 年左右没有飞跃;P

标签: grails formatting gsp taglib


【解决方案1】:

您可以创建一个标签库:将SecondsTagLib.groovy 放入grails-app/taglib/(位置和类名中的后缀TagLib 都很重要)。

class SecondsTagLib {
  def formatSeconds = { 
    attrs, body ->
      final int hours = attrs.seconds / (60 * 60)
      final int remainder = attrs.seconds % (60 * 60)
      final int minutes = remainder / 60
      final int seconds = remainder % 60

      out << hours.toString().padLeft(2, "0") + ":" + minutes.toString().padLeft(2, "0") + ":" + seconds.toString().padLeft(2, "0")
  }
}

并在您的视图中使用该标记库:

<html>
  <body>
    Seconds: ${seconds} = <g:formatSeconds seconds="${seconds}"/>
  </body>
</html>

控制器的方法可能如下所示:

class TagLibController {
  def seconds() { 
    // 10:11:01
    def seconds = (10 * 60 * 60) + (11 * 60) + 1
    def model = ["seconds": seconds]
    render(view: "seconds", model: model)
  }
}

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2015-10-12
    相关资源
    最近更新 更多