Home > Enterprise >  How can I show month and year in 12's timezone in swift?
How can I show month and year in 12's timezone in swift?

Time:10-12

func getMonYearDateFormat() -> String {
            let dateFormatter = DateFormatter()//EEEE, d, MMM
            dateFormatter.dateFormat = is24Hour() ? "yyyy-MM-dd' 'HH:mm:ss" : "yyyy-MM-dd' 'h:mm:ss a"
            dateFormatter.timeZone = TimeZone.current
            dateFormatter.locale = Locale.current
            guard let oldDate = dateFormatter.date(from: self) else { return "" }
            let convertDateFormatter = DateFormatter()
            convertDateFormatter.dateFormat = "MMMM yyyy"
            
            return convertDateFormatter.string(from: oldDate)
        }

I show month and year as title in table view. I wrote this function to convert the date of the relevant card to month and year. If the device is in the 24-hour time zone, the function works properly. However, if the device is in the 12th time zone, it returns blank and I cannot see the month and year of the relevant card. I couldn't find the part that I wrote incorrectly in the function.

CodePudding user response:

I've tested your code with 12 hour format and it works. The only thing I've. change is to use the 12 hour format without call is24Hour() because you did not provide that code. So I suspect the point of failure is the is24Hour() function.

CodePudding user response:

As mentioned in the comments I would recommend you to investigate how you get this string and if possibly use the original Date object instead if it exists but below is a solution that I think handles the 12 vs 24h issue in an efficient way.

The logic is to first convert using 24h and if that returns nil then convert using the 12h format.

I have declared all formatters I use as static properties so they only get created one since creating a DateFormatter is expensive

extension String {
    private static let formatter24: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
        return dateFormatter
    }()
    private static let formatter12: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd' 'h:mm:ss a"
        return dateFormatter
    }()
    private static let formatterMonthYear: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMMM yyyy"
        return dateFormatter
    }()

    func getMonYearDateFormat() -> String {
        let date = Self.formatter24.date(from: self) ?? Self.formatter12.date(from: self)
        guard let date else { return "" }

        return Self.formatterMonthYear.string(from: date)
    }
}
  • Related