繁体   English   中英

如何使用 Vapor 4 在 Leaf 模板中格式化日期字段

[英]How to format a date field in a Leaf template using Vapor 4

在列表中,我想显示从数据库中获取的日期。 如果我使用:

#Date(timeStamp: appointment.appointmentDate,localizedFormat: "E, dd-MM-yyyy")

我希望:星期三, 2020年 12 月 30 日,但我得到了星期三, 2020年 12 月 30 日,我觉得这很奇怪,因为我特别要求dd-MM

然后我尝试了:

#Date(timeStamp: appointment.appointmentDate,fixedFormat: "E, dd-MM-yyyy")

工作正常并为我提供:星期三,2020 年 12 月 30 日

不过,我还是不开心……

  1. 我想用 - 而不是 / 呈现它:星期三,2020 年 12 月 30 日

  1. 由于我的应用程序将被本地化,我想控制显示日期的方式:Wed (Eng)、Mer(French)、Woe (Dutch) 那么如何设置应在 Leaf 中使用的区域设置? (我知道如何在 Vapor 中做到这一点,但如果可能的话,我宁愿把它留给 Leaf。)

创建叶子方法:

import Foundation
import Leaf

public struct DataLeafFunction: LeafFunction, StringReturn, Invariant {

    public static var callSignature: [LeafCallParameter] { [
        .double,
        .string(labeled: nil, optional: true, defaultValue: "yyyy-MM-dd")
    ] }

    public func evaluate(_ params: LeafCallValues) -> LeafData {
        guard let timestamp = params[0].double else { return .string(params[0].string) }

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = params[1].string
        let date = Date(timeIntervalSinceReferenceDate: timestamp)

        return .string(dateFormatter.string(from: date))
    }
}

添加function配置:

func configure(_ app: Application) throws {
     LeafEngine.entities.use(DataLeafFunction(), asFunction: "date")
     // ...
}

在您的模板中使用此 function:

#date(date) 
#date(date, "YY/MM/dd")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM