I have a DateTime that I'm reading from an API that is in GMT.
I want to force cast it to an EST date object.
The original object is a string that I then cast to a Date to do some time comparison. Unfortunately, I don't think I did this right which made me do this unholy abomination:
extension String {
//this force casts from our original data being in GMT to EST
func getDateTimeTZ() -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
if let date = dateFormatter.date(from: self) {
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
let localTime = dateFormatter.string(from: date)
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
return dateFormatter.date(from: localTime)!
}
return dateFormatter.date(from: self)!
}
}
For whatever reason, I seem to have to flip the dateformatter 3 times to get the correct EST string output. Is there a better way to do this?
A Date is not associated with a time zone. From the Date reference:
A specific point in time, independent of any calendar or time zone.
...
A Date value encapsulate a single point in time, independent of any particular calendrical system or time zone. Date values represent a time interval relative to an absolute reference date.
So there is no such thing as “an EST date object” in the iOS SDK.
Time zones are relevant when converting to or from strings and when manipulating the calendrical components (year, month, day, hour, minute, second, etc.) of a Date.
The code you posted computes a new Date that is offset from the original date by the time offset between GMT and EST, but the new Date is not “an EST date object”.
(Incidentally, "EST" means Eastern Standard Time, and will not switch to daylight saving time during the appropriate part of the year. Use "US/Eastern" to get the appropriate time conversion depending on the day of year.)
You say you're doing this adjustment “to do some time comparison”, but you don't say what you're comparing to. It would help for you to describe what comparison you're performing.
For example, let's you want to check whether the Date is in the range 8:30 AM to 3:00 PM in the US/Eastern time zone, regardless of the day. If the input string is GMT, then you should parse it that way, as you do in your code:
let parser = DateFormatter()
parser.timeZone = TimeZone.init(identifier: "GMT")
parser.dateFormat = "yyyy-MM-dd HH:mm"
let date = parser.date(from: "2021-03-26 19:55")!
Then, use a Calendar set to the "US/Eastern" TimeZone to compute the hour and minute components of the Date:
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "US/Eastern")!
let components = calendar.dateComponents([.hour, .minute], from: date)
let hhmm = components.hour! * 100 + components.minute!
if (08_30 ..< 15_00).contains(hhmm) {
print("school time")
} else {
print("play time")
}
Related
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.
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
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))
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.
I would like to convert any time, UTC,, GMT+2 .. etc , anything to be only GMT +3
I tried this code but no success
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.timeZone = TimeZone.current
let currentdate = formatter.string(from: date)
print("currentdate \(currentdate)")
let gmt = DateFormatter()
gmt.timeZone = TimeZone(secondsFromGMT: 3600*3)
gmt.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let gmtDate = gmt.date(from: currentdate)!
print("gmtDate -> \(gmtDate)")
I tried abbreviations for the time zone, same result the date comes out to be only GMT.
Any ideas?
Your code has a lot of issues. First, there is no reason to go from Date to String and back to Date. Second, if you are converting a String to a Date, and the String contains its own timezone information, then setting the formatter's timeZone is pointless. The timezone in the string will be used when calculating the associated Date. There are only two cases where setting a date formatter's timezone makes sense:
When parsing a date/time string that does not contain any timezone information. The formatter's timezone will then be used to interpret the string.
When converting a Date to a String. The formatter's timezone will be used when generating the resulting string from the date.
If you simply want to show any Date as a String in a specific timezone then all you need is:
let date = Date() // some date
print("Original Date (in GMT): \(date)")
// Setup a formatter with a date and time style
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 3600 * 3) // the desired timezone
formatter.dateStyle = .long
formatter.timeStyle = .medium
let string = formatter.string(from: date)
print("GMT+3 style result: \(string)")
// For comparison, set the formatter to a specific format
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let string2 = formatter.string(from: date)
print("GMT+3 format result: \(string2)")
Output (for the en_US locale):
Original Date (in GMT): 2017-10-28 20:53:59 +0000
GMT+3 style result: October 28, 2017 at 11:53:59 PM
GMT+3 format result: 2017-10-28 23:53:59 +0300
There is no need to convert any time. Simply create a String from a Date to get the desired output.
Note that, by default, a DateFormatter shows its result in local time. Set the formatter's timeZone if you want the result in some other specific timezone.
Also note that printing a Date object always shows the date in UTC time (+0000). Many people get confused by this and think they are getting the wrong date when they are not.
Swift 5
private func convertDate(string:String) -> String {
let dateFormatter = DateFormatter()
// format in which the date and time comes from the server
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
// set the time zone, the time is stored on the server
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3")
// convert to Date
let date = dateFormatter.date(from: string)
// now set our local time zone
dateFormatter.timeZone = TimeZone.current
// time format we need
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
// convert the Date obtained above into text format
let displayString = dateFormatter.string(from: date!)
// local time is ready)))
return displayString
}