0
func getDateWithoutTimeForDisplay() -> String {
    let formatter = DateFormatter()
    //     formatter.locale = Locale(identifier: "en_US")
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    formatter.timeZone = TimeZone(identifier: "UTC")
    formatter.locale = Locale(identifier: "en_US_POSIX")
    let myStringafd = formatter.date(from: self)

    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy"
    dateFormatter.timeZone = NSTimeZone.local
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    if let myStringafd =  myStringafd {
        let somedateString = dateFormatter.string(from: myStringafd)
        return somedateString
    }
    return ""
}

this is my code to convert given UTC date to system date based on the local time zone. The actual problem is, suppose the case "i have the time 1.00 AM on the date 25-08-2020, according to the Indian time zone, ( UTC time is 5.30 lesser than Indian time) the corresponding UTC date is 24-08-2020 due to the time difference with the Indian time". In this case i want to convert the UTC date(Because it is effecting the date to be display for the user) to the current system date.

My system date&time is 25-08-2020 1:00 AM (Indian time) the corresponding UTC date is 24-08-2020. -5:30 hr

i need to convert the UTC date to the current local time

TheAppMentor
  • 1,091
  • 7
  • 14

1 Answers1

0

Try this out:

let currentDate = self.UTCToLocal(date: Date().description) //This will pass system date in UTC format to the function and function will return desired output in local timezone

func UTCToLocal(date: String) -> String {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssz" //The date format should be exact as same as UTC date
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = NSTimeZone.local
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" //The desired date format in which you may want to return the value
    
    return dateFormatter.string(from: dt!)
}

or you can check this post - Returning nil when converting string to date in swift and this link for dateFormatters - https://nsdateformatter.com/

Parth Patel
  • 1,250
  • 1
  • 13
  • 21
  • i want to convert UTC formatted date to system date. i have UTC date in myStringafd variable. i want to convert that to local – Mohammed Ramshad .k Aug 25 '20 at 07:12
  • @MohammedRamshad.k if you print a Date() then it will show UTC date something like this 2020-08-25 07:17:00 +0000 and for clear understanding you may visit this link - http://ios-tutorial.com/working-dates-swift/. This function works for me. – Parth Patel Aug 25 '20 at 07:20
  • i have edited my question. i think you may have to understand the exact scenario for my problem – Mohammed Ramshad .k Aug 25 '20 at 08:44
  • Please check the edited answer now. It should work. – Parth Patel Aug 25 '20 at 09:44