Search code examples
iosswifttimestampgoogle-analytics-4dataformat

DateFormatter returns incorrect year in formatted timestamp on iOS


I am currently working on an iOS application and I'm encountering a peculiar issue with date formatting. I am using the following Swift code to generate a timestamp in a specific format and log it to Google Analytics4:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSXXX"
let currentDate = Date()
let formattedDate = dateFormatter.string(from: currentDate) // 2024-04-20T21:23:42.22+09:00

The dateFormat I am using is supposed to format the current date and time in the ISO 8601 format. However, while the expected behavior is to get the current year (e.g., 2024), the formatter sometimes returns years like 2567 or 0006.

This incorrect year data appears sporadically among different user devices and does not correlate with any specific iOS version or device model. The majority of timestamps are correct, but these outliers are concerning.

Could anyone help me understand why this might be happening? Is there something wrong with the way I am using DateFormatter? Any advice on how to ensure the year is always correctly captured would be greatly appreciated.

Thank you!


Solution

  • You should use a date formatter in a correct Locale. From my project there's an extension, could you please try to use one of the following:

    extension DateFormatter {
    
     static let iso8601: ISO8601DateFormatter = {
        
        let formatter = ISO8601DateFormatter()
        return formatter
     }()
    
     static let iso8601Custom: DateFormatter = {
        
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        formatter.calendar = Calendar(identifier: .gregorian)
        
        return formatter
     }()
    }