2

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.)
Nick
  • 4,820
  • 18
  • 31
  • 47
Glenn
  • 2,808
  • 2
  • 24
  • 30

1 Answers1

2

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")
myrkwill
  • 21
  • 4