简体   繁体   中英

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

In a list, I want to show dates fetched form the database. If I use:

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

I would expect: Wed, 30/12 /2020 BUT I get Wed, 12/30 /2020 which I find very strange since I specifically ask for dd-MM

I then tried:

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

with works okay and provides me with: Wed, 30/12/2020

However, I'm still not happy...

  1. I want to have it presented with - instead of /: Wed, 30-12-2020

and

  1. Since my app will be localized, I would like to have control on the way the day is shown: Wed (Eng), Mer(French), Woe (Dutch) so how do I set which locale should be used in Leaf? (I know how to do it in Vapor but I'd rather leave it up to Leaf if it is possible.)

Create Leaf method:

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))
    }
}

Add function to configure:

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

Use this function in your templates:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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