Date format giving wrong year

        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        formatter.calendar = Calendar.init(identifier: .gregorian)
        let strdate = formatter.string(from:Date())
        let myDate = IMUtil.stringtoDateConverter(startDateString: strdate)
        formatter.dateFormat = "yyyyMMddHHmmss"
        guard let timeZone = NSTimeZone(name: "UTC") as TimeZone? else {
            return
        }
        formatter.timeZone = timeZone
        if startIndex == 0 {
            currentDate = formatter.string(from: myDate)
        }

I'm using above code to create a date .

Expected response :

20240104190840

Response :

14810104190840

Why is it giving wrong year?

Replies

What is this line? What is IMUtil? Is the returned value of myDate what you expect?

let myDate = IMUtil.stringtoDateConverter(startDateString: strdate)

BTW, for working with fixed-format dates, see this thread and consider using ISO8601DateFormatter.

    static  func stringtoDateConverter(startDateString : String) -> Date {
        
        // create   date from string
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        dateFormatter.timeZone = NSTimeZone.local
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        
        let startDate = dateFormatter.date(from: startDateString)// create   date from strinG
        return startDate!
        
    }```


This is the code for the above function call.