Adding Time Offset in Swift

Adding Time Offset in Swift

If you want to convert a show time which is stored as a string in GMT, and you want to show it in the user's local time zone, you should not be manually adjusting the NSDate/Date objects. You should be simply using the appropriate time zones with the formatter. For example, in Swift 3:

let gmtTimeString = "5:00 PM"

let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = TimeZone(secondsFromGMT: 0) // original string in GMT
guard let date = formatter.date(from: gmtTimeString) else {
print("can't convert time string")
return
}

formatter.timeZone = TimeZone.current // go back to user's timezone
let localTimeString = formatter.string(from: date)

Or in Swift 2:

let formatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) // original string in GMT
let date = formatter.dateFromString(gmtTimeString)

formatter.timeZone = NSTimeZone.localTimeZone() // go back to user's timezone
let localTimeString = formatter.stringFromDate(date!)

How to get timezone offset as ±hh:mm?

Some integer arithmetic to obtain the offset in hours and
minutes:

let seconds = TimeZone.current.secondsFromGMT()

let hours = seconds/3600
let minutes = abs(seconds/60) % 60

Formatted printing:

let tz = String(format: "%+.2d:%.2d", hours, minutes)
print(tz) // "+01:00"

%.2d prints an integer with (at least) two decimal digits (and leading
zero if necessary). %+.2d is the same but with a leading + sign for
non-negative numbers.

Calculate date time by adding / subtracting local offset [ Convert any date time , to UTC time format]

Solved this by using localoffset coming from service and with the method available in swift , TimeZone(secondsFromGMT:offset) :

func findFlightTimeInUTCFormat(dateString:String, localOffSet:String) -> Date? {
let gmtTimeString = dateString

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(secondsFromGMT: -6*60*60)
var finalDate:Date?
// original string in GMT
guard let date = formatter.date(from: gmtTimeString) else {
print("can't convert time string")
return finalDate
}
finalDate = date
return finalDate
}

Solved and its working fine.

Swift: get the offset value from a date object

If I understand you correctly you want only the date and time portion ignoring always the time zone information.

In this case strip the time zone from the date string with regular expression

let dateString = "2017-05-01T12:30:00-0700"
let dateStringIgnoringTimeZone = dateString.replacingOccurrences(of: "[+-]\\d{4}", with: "", options: .regularExpression)
print(dateStringIgnoringTimeZone) // "2017-05-01T12:30:00"
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = dateFormatter.date(from: dateStringIgnoringTimeZone)!

Applying timezone offset data provided by OpenWeatherMap (Swift)

you could try something simple, like this example code, to get the time at the "other" location:

let timeHere = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL dd, hh:mm:ss a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: response.timezone_offset) // <-- here

let timeThere = dateFormatter.string(from: timeHere)

print("timeHere: \(timeHere) timeThere: \(timeThere) \n")

Absolute UTC offset in Swift

A few things:

  • In your tests, you have the offsets for Warsaw and Lisbon an hour off. Warsaw is UTC+1 during standard time, and UTC+2 during daylight saving time. Lisbon is UTC+0 during standard time, and UTC+1 during daylight time.

  • From your comment, it seems you're looking for the standard offset and the daylight offset. However, the standard offset isn't necessarily the same as the current offset. The current offset might include daylight saving time, or not.

  • According to these docs, the secondsFromGMT function returns the difference including the daylight adjustment if one is in effect. Thus you should not be adjusting for that yourself.

  • It doesn't seem to make sense to be asking the daylightSavingTimeOffset function for the offset on a date when daylight saving time doesn't apply. You might get better results just using secondsFromGMT for two different dates in the current year. A common approach is to get the offsets for January 1st and July 1st. Whichever is smaller is the standard time, the other is the daylight time. Keep in mind they may be the same if DST is not used, and they will be inverted between northern and southern hemisphere time zones.

    • Even with the above approach, this sort of algorithm ignores a lot of the complexities of time zones. Consider that some time zones have changed their standard time at different points in their history. Such an algorithm might mistake that as a daylight saving time change.
  • A point of concern: Once you have your string generated, such as "UTC+1UTC+2", how will the external API you know from that alone which set of daylight saving time rules to apply? Since daylight saving time starts and stops at different dates and times in different parts of the world, it's likely that the wrong dates could be used when interpreting the offsets.

How to get timezone offset between UTC and iPhone - Swift 4.2?

You can get the current timezone, get the number of seconds from GMT and divide it by 3600.

TimeZone.current.secondsFromGMT() / 3600    // -3 hs America/Sao_Paulo (current) Brazil

If you need more precision like fraction of hour as well just convert it to double before dividing it.

Create TimeZone object from timeZoneOffset string?

My suggestion is to use DateFormatter which is able to parse the time zone string format. refZoneString is the reference to UTC in the current time zone.

extension TimeZone {

init?(UTCOffsetString ofs: String) {
let refZoneString = "+0000"
let formatter = DateFormatter()
formatter.dateFormat = "Z"
guard let refDate = formatter.date(from: refZoneString),
let date = formatter.date(from: ofs) else { return nil }
self.init(secondsFromGMT: Calendar.current.dateComponents([.second], from: date, to: refDate).second!)
}
}

let tz = TimeZone.init(UTCOffsetString: "-07:30")
print(tz?.identifier ?? "unknown")


Related Topics



Leave a reply



Submit