Home > Software design >  Parse a String to a Date using Date.ParseStrategy
Parse a String to a Date using Date.ParseStrategy

Time:06-20

I would like to parse a 06/19/2022 01:00 PDT date.

Using a new Date.ParseStrategy(format:) i wrote this:

import Foundation


let dateFromNetwork = "06/19/2022 01:00 PDT"

let strategy = Date.ParseStrategy(format: "\(month: .twoDigits)/\(day: .twoDigits)/\(year: .defaultDigits) \(hour: .twoDigits(clock: .twelveHour, hourCycle: .zeroBased)):\(minute: .twoDigits)", timeZone: .init(abbreviation: "PDT")!)

let date = try! Date(dateFromNetwork, strategy: strategy)
// Cannot parse 06/19/2022 01:00 PDT
// String should ahere to specified format, such as 06/20/2022 01:00

How to deal with latest part of timezone PDT?

CodePudding user response:

Try this strategy:

let strategy = Date.ParseStrategy(format: "(month: .twoDigits)/(day: .twoDigits)/(year: .defaultDigits) (hour: .twoDigits(clock: .twelveHour, hourCycle: .zeroBased)):(minute: .twoDigits) PDT", timeZone: .init(abbreviation: "PDT")!)

In your case, You're not using timeZone in your format.

  • Related