How to convert a date to a specific timezone when user is in a different timezone? - swift

I have a problem in handling dates in Swift in different timezones. I'm getting an Italian date from my server and I'm trying to convert it into a Date through the following function:
func stringToDateTime(dateString: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.locale = Locale(identifier: "it_IT")
formatter.timeZone = TimeZone(identifier: "Europe/Rome")
return formatter.date(from: dateString)
}
However if the date is "2022-11-22 10:00:00", for example, and I'm in London or New York the function returns:
▿ 2022-11-22 09:00:00 +0000
- timeIntervalSinceReferenceDate : 690800400.0
Why is that so? I specified the timezone in the formatter so it should return me 10 o'clock. What am I doing wrong?

The date and time seems correct to me.
The date and time which was passed "2022-11-22 10:00:00" is in Italian time, which is GMT+1, or with other words, 1 hour ahead of UTC.
The date and time which was printed to the console is in UTC, or GMT+0, and is indicated by '+0000'.
2022-11-22 09:00:00 +0000
If we were to put this date into a converter for UTC to Italian time, we would get the initial value - "2022-11-22 10:00:00".
When you print a Date in the console directly, it automatically uses UTC as the time zone. If you'd like to print a string representation of your Date object to the console in your locale, use this method:
Generates a locale-aware string representation of a date using the default date format style.
func formatted() -> String
from Apple documentation: https://developer.apple.com/documentation/swift/sequence/formatted(_:)

Related

How to parse date in "2022-03-04T10:30:00-08:00" format correctly in swift?

I have date coming from API shown below. These dates are for different countries.
dateTime = "2022-03-04T14:30:00-08:00"
I need to convert this use it both as Date and as String. But I do not know if date and time I am converting are correct. I am using following code:
To Convert String from API to Date:
extension String {
var CommonDateFormat: Date? {
get {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return dateFormatter.date(from: self)
}
}
}
To Convert Date to String:
extension Date {
func getDateAccoringTo(format: DateFormat ) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format.rawValue
dateFormatter.timeZone = .current
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
return dateFormatter.string(from: self)
}
}
enum DateFormat: String {
case ddmmyyyy = "dd/MM/yyyy"
case mmddyyyy = "MM/dd/yyyy"
case mmmd_yyyy = "MMM d, yyyy"
case llll_yyyy = "LLLL ,yyyy"
case TIME = "HH:mm:ss"
case day = "dd"
}
When I try to get day from date it always gives next day date. For example if date = "2022-03-04T14:30:00-08:00" then if I try to get day using code below
date?.getDateAccoringTo(format: .day)
This returns 5 not 4
date?.getDateAccoringTo(format: .TIME)
This returns time 00:00:00
Am I missing something important which is leading to these values?
Also, if I am missing something in my question kindly let me know so that I can improve it.
The given string
let dateTime = "2022-03-04T14:30:00-08:00"`
is a standard ISO8601 formatted date string. It can be converted to Date with
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: dateTime)!
At this specific point in time it is
14:30 on Friday, March 4 in Denver, CO, USA
22:30 on Friday, March 4 in London, UK
06:30 on Saturday, March 5 in Tokyo, Japan
Now let's see how Xcode displays dates.
print displays Date instances always in UTC indicated by +0000 which is the London time zone unless you print(date.description(with: .current), this displays the date in the local time zone.
In a Xcode Playground the result area displays Date instances in the local time zone except in print lines.
Last point to consider is that DateFormatter converts Date to String in the local time zone if no time zone is specified.
Keeping this behavior in mind you get the next day if you convert the date to string with DateFormatter but without specifying the time zone and your local time zone is greater than or equal to +01:30.
And you get the time 00:00 if you convert the date to string with DateFormatter but without specifying the time zone and your local time zone is exactly +01:30 which is a pretty unusual time zone by the way.

How can I ignore time zones in Swift Dates?

I wish to use Swift 5 to create a Date object with the day, month, and year I pass it. Problem is that the DateFormatter has its own ideas, and seems to be treating my Date objects as if they were UTC even whatever I set <formatter>.timeZone = ... to.
Say I want t date object with the date the first of April.
private func firstOfApril() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return "\(formatter.date(from: "2021-04-01")!)"
}
If I do this in the AM here (GMT + 13) I get 2021-03-31 11:00:00 +0000. I expect: 2021-04-01 00:00:00
WHat I have tried:
enum TZType{
case None
case Current
case Auto
case Nil
case Default
}
private func firstOfApril(none_current:TZType) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
switch none_current {
case .None:
formatter.timeZone = .none
case .Current:
formatter.timeZone = .current
case .Nil:
formatter.timeZone = nil
case .Auto:
formatter.timeZone = .autoupdatingCurrent
case .Default:
break
}
return "\(formatter.date(from: "2021-04-01")!)"
}
print(firstOfApril(none_current: .None))
print(firstOfApril(none_current: .Current))
print(firstOfApril(none_current: .Auto))
print(firstOfApril(none_current: .Nil))
print(firstOfApril(none_current: .Default))
Outputs
2021-03-31 11:00:00 +0000
2021-03-31 11:00:00 +0000
2021-03-31 11:00:00 +0000
2021-03-31 11:00:00 +0000
There is no concept of time zones in my application. I think there should be, but I am overruled. All time is "local time", as in wall clock time, not local time zone.
Leo got it.
The last lines of that function should be:
let retDate = formatter.date(from: "2021-04-01")!
return formatter.string(from: retDate)
In total:
private func firstOfApril(none_current:TZType) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
switch none_current {
case .None:
formatter.timeZone = .none
case .Current:
formatter.timeZone = .current
case .Nil:
formatter.timeZone = nil
case .Auto:
formatter.timeZone = .autoupdatingCurrent
case .Default:
break
}
let retDate = formatter.date(from: "2021-04-01")!
return formatter.string(from: retDate)
}
You've gotten some good, but incomplete, information.
A Date object captures a moment in time, anywhere on the planet. It is devoid of a time-zone. (Internally, it's recorded by a number of seconds since the iOS/MacOS "epoch date", or "zero date". That zero date is in UTC.)
Date objects don't have a time zone, but they also don't have a fixed time or date. The same instant in time will be at different times of day in different time zones, and may even be different dates (e.g. It is about 7 PM on Monday 29 March here in the US Eastern Daylight Time timezone. It is about midnight on Tuesday 30 March in London.)
If you create a date formatter and feed it a month/day/year, it will default to creating a Date object using your local time zone. It's not the Date object that has a time zone, it's the date formatter.
You can either use the date formatter you already created to convert you dates back to strings (using the DateFormatter function string(from:), or you can use a DateFormatter class function called localizedString(from:dateStyle:timeStyle:. That function takes a date and displays it in your local time zone, using the conventions of your locale, and lets you specify short, medium, or long format dates.
If you write
let date = Date()
print(DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium))
You'll get something like this:
Mar 29, 2021 at 7:07:13 PM
That is expressed in my local time zone, using US date and time formats.
(But with the date and time at which you run it, and using the date and time formatting conventions for your locale.)
Next, it's how you display the date. If you write the code
print(Date())
What you will see is the date at the instant you run the code, but expressed in UTC. For me, that will be 4 hours ahead of my current time, so it will claim it's about 23:00 on 30 January.
2021-03-29 23:00:48 +0000
If you are in China, and I am in the US, and our phones' clocks are both synchronized exactly, and we capture the current date using Date() at the same instant, we will get the exact same Date value. If we were to both express it in UTC, it would show the same date and time. (The Date object doesn't have a time

Converting string to date with a different timezone gives the wrong date

So, this:
import Foundation
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
df.timeZone = TimeZone(identifier: "Australia/Currie")!
let todayString = (df.string(from: Date()))
print(todayString)
let today = df.date(from: todayString)!
print(today)
Prints:
2021-02-19
2021-02-18 13:00:00 +0000
For reference, today’s date based on my current timezone is the 18th. So it correctly prints the 19th when using an Australian timezone that moves the time ahead.
What I don't understand is why today is a day behind todayString, since it's constructed from the same DateFormatter. Ideally, they should both print the 19th, right?
Basically, what I'm trying to do is have both a date (from a different timezone) and its string representation.
As mentioned in the comments print displays Date instances always in UTC(+0000). For example check
let date = Date()
print(date)
To print the date in your current locale (and time zone) write
print(today.description(with: .current))

how to convert a String to a Date without changing the Format

I'm using Xcode 11.4.1
In my Project I got a String with some data which I need to split up and save the Information in some variables.
now I face a problem if I try this
let dateString = "12-04-2020"
let dateFormatIn = DateFormatter()
dateFormatIn.dateFormat = "dd-MM-yyyy"
let saveDate: Date = dateFormatIn.date(from: dateString)!
print("The date is: \(saveDate)")
the result which I expected is "The date is: 12-04-2019" but what I got is "The date is: 2020-04-11 15:00:00 +0000"
what do I miss, what is this printed Date? it's not the current date ans also not the String!
I need the Date in the same format as I got it in the String.
A Date is a point in time, it doesn't have a format nor a time zone.
print shows the description – a string representation – of the date in the UTC time zone.
Your time zone is obviously UTC +0900, 2020-04-12 00:00:00 +0900 and 2020-04-11 15:00:00 +0000 is the same point in time.
If you want to create the date string independent of the time zone add the line
dateFormatIn.timeZone = TimeZone(secondsFromGMT: 0)
let saveDate: Date = dateFormatIn.date(from: dateString)!
The ": Date" looks like a data type declaration. You're saying, "create a variable called saveDate of type Date, and initialize it from the output of dateFormatIn.date(from: dateString)".
So you're not printing the formatted output. You're converting the formatted output to a new Date object, and then printing that.
Try:
let saveDate = dateFormatIn.date(from: dateString)!
This should save whatever dateFormatIn.date(from: dateString) returns in saveDate.

How to convert time between timezones taking daylightsavings into account?

I have the following function for converting time:
static func convert(date: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "h:m:s a"
formatter.timeZone = TimeZone(identifier: "UTC")
let convertedDate = formatter.date(from: date)
formatter.timeZone = NSTimeZone.local
return formatter.string(from: convertedDate!)
}
Since I'm setting the new time zone based on the device's time zone I taught that daylight savings will be taken into account. But when I passed in 2:00:00 PM it returned 3:0:0 pm instead of 4.
Am I missing something, is there an automatic way to correctly convert time between time zones?
Dealing with daylight saving time only makes sense when the date is known. You don't have a date, just a time. So convertedDate will be January 1, 2001. So whatever the daylight saving rule is for the user's timezone and locale on that date will be used when converting the time.
If you want the time to be treated as "today" then you can set the date formatter's defaultDate.
formatter.defaultDate = Date()
If you want some other specific date, create a Date as needed and use that to set the defaultDate.