How to change a string for today without converting to any time zone in Swift?

I know that there are many questions around this simple problem, but I still could not understand.

Here is what I want:

SelectedDateString = "19-08-2015 09:00 AM" let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm a" dateFormatter.timeZone = NSTimeZone(); let SelectedUTCDate = dateFormatter.dateFromString(SelectedDateString)! println("SelectedLocalDate = \(SelectedLocalDate)") // OUTPUT: SelectedLocalDate = 2015-08-18 18:30:00 +0000 

If I do not use TimeZone:

  let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm a" // dateFormatter.timeZone = NSTimeZone(); let SelectedUTCDate = dateFormatter.dateFromString(SelectedDateString)! println("SelectedLocalDate = \(SelectedLocalDate)") //OUTPUT: SelectedLocalDate = 2015-08-18 19:26:00 +0000 

Why does the time and date change? I want to:

 //OUTPUT: SelectedLocalDate = 2015-08-19 09:00:00 +0000 

I also want to convert the local date to the exact UTC date

 //Like this: SelectedUTCDate = 2015-08-19 03:30:00 inputString = "19-08-2015 10:45 am" // My localtime is 10:35 AM, so I set 10 mins from now var currentUTCTime = NSDate() // currentUTCTime is 05: 15 AM. 

I want to convert inputString to the appropriate UTC time and find the difference between the two points in both the date and the string.

 //Like this Date: diffInDate: 00-00-0000 00:10 and // Like this String: diffInString: 10 mins 

How can I get both of them?

+4
source share
1 answer
 let dateString = "19-08-2015 09:00 AM" let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy hh:mm a" dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601) dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) if let dateFromString = dateFormatter.dateFromString(dateString) { print(dateFromString) // "2015-08-19 09:00:00 +0000" dateFormatter.dateFormat = "dd-MM-yyyy hh:mm a Z" dateFormatter.timeZone = NSTimeZone.localTimeZone() dateFormatter.stringFromDate(dateFromString) // 19-08-2015 06:00 AM -0300" } 
+6
source

All Articles