0

I am trying to convert UTC Date to local date in swift but after get UTC To Local date in string i convert that string to again in NSDate but i am always getting in UTC date format, below is my code

Date : in UTC : 2016-07-20 18:30:00 +0000

I am trying this date in local date, check below code:

let dateInUTC = NSDate()
        let seconds: Int = NSTimeZone.systemTimeZone().secondsFromGMT
        print(seconds)
        let localDateFormatter: NSDateFormatter = NSDateFormatter()
        localDateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
        localDateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: seconds)
        let lastDate: String = localDateFormatter.stringFromDate(dateInUTC)
        print(lastDate)

at this time i am getting “07/12/2016 16:56:36 GMT+5:30”, means i got local date in string but i want this date in NSDate so again i convert this string date in NSDate,check below

    let getDate:NSDate = localDateFormatter.dateFromString(lastDate)!
    print(getDate)

but at this stage again i got date in UTC (2016-07-12 11:26:36 +0000) but i want in local date,

  • I tried a lot of times in Swift but not getting local date from string,this line of code i used in objective-c, its working fine in obj-c but when i am trying in swift i always get UTC date,suggest me and give me right way to sol this.
Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
  • 2
    NSDate represents an absolute point in time and HAS NO TIMEZONE. This has been asked and answered repeatedly. – Martin R Jul 12 '16 at 11:44
  • so how to get NSDate with local timezone? (note : Not in string, it should be in NSDate) – Bhavesh Nayi Jul 12 '16 at 11:52
  • That question makes no sense, NSDate is just the number of seconds since the January 1, 2001 GMT. See for example http://stackoverflow.com/questions/24917483/swift-nsdate-utc-time-and-local-tme or http://stackoverflow.com/questions/18124684/nsdate-change-time-zone. The *description* method of NSDate uses UTC to present the date as a string. – Martin R Jul 12 '16 at 11:53
  • *"its working fine in obj-c"* – There is no difference between Objective-C and Swift with respect to NSDate. Please show your Objective-C code and the output. – Martin R Jul 12 '16 at 12:21

1 Answers1

1

NSDates don't save time zone information. You always have to use the dateFormatter with time zone when retrieving.

Tim
  • 2,089
  • 1
  • 12
  • 21