iOS Swift: how to convert specific date string format to Date object, when string contains time zone abbreviation? - ios

I am getting a date string from server in the format of "March 08, 2018 16:00:00 PST" where there is a lot of whitespace between Month & Date.
My intention is to basically remove those extra whitespaces. My idea is that- I will convert the string into Date object, and then convert back to string.
How can I convert this into Date object using Date Formatter, taking timezone into consideration.
I am concerned about the "PST" here. While converting the Date to String, I will need in the format - "March 08, 2018 16:00:00 PST" i.e. PST (or whatever time zone comes in) should stay intact in the final string.

extension String {
func getDate(fromFormat format: String = "MMMM dd, yyyy HH:mm:ss zzz") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self)
}
}
let myDateString = "March 08, 2018 16:00:00 PST"
myDateString.getDate()
You can call with other time formats too.

Try this
let isoDate = "March 08, 2018 16:00:00 PST"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm:ss z"
let date = dateFormatter.date(from: isoDate)!

Try this
class func stringToDate (dateString:String, dateFormat:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let dateFromString = dateFormatter.date(from: dateString)
return dateFromString
}

Related

Convert string containing date to Date

I'm having issues converting a string to date on swift, maybe it is something obvious but I don't get it.
I'm trying to convert "Jan 18, 2022 04:39PM GMT" this string into a Date. My code looks like this:
let str = "Jan 18, 2022 04:39PM GMT"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, YYYY hh:mma z"
let date = dateFormatter.date(from: str)
print(date)
And console shows: Optional(2021-12-19 16:39:00 +0000)
Any idea what's wrong in this formatter?
In addition to the Date being shown as an Optional, your format string appears to be wrong. "YYYY" should be "yyyy", so the whole line that assigns the formatter should be:
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"
That change yields the output
"Optional(2022-01-18 16:39:00 +0000)"
In addition, you should really force the calendar to Gregorian or iso8601, and set its locale to "en_US_POSIX:
An improved version of the date formatter could would look like this:
(from Leo's edit.)
let str = "Jan 18, 2022 04:39PM GMT"
let dateFormatter = DateFormatter()
dateFormatter.calendar = .init(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"
if let date = dateFormatter.date(from: str) {
let dateString = dateFormatter.string(from: date)
print(dateString == str) // true
}
The code written for converting date is correct, also converted date is correct. But final result is optional so you are getting date like Optional(2021-12-19 16:39:00 +0000).
Also the date formatter is wrong.
So please unwrap the date to get actual date without optional.
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"
guard let convertedDate = date else {
return
}
print(convertedDate)

How to convert string to date correctly? [duplicate]

This question already has answers here:
NSDateFormatter still parsing instead having incorrect format
(3 answers)
Closed 3 years ago.
Why does dateFormatter return the correct date from an invalid format string?
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020/////07////////10") //"Jul 10, 2020 at 12:00 AM"
I will say more - it also works unexpectedly
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dotDate = dateFormatter.date(from: "2020....07...10") // Optional(2020-07-09 21:00:00 +0000)
let commaDate = dateFormatter.date(from: "2020,,,,07,,,,10") // Optional(2020-07-09 21:00:00 +0000)
My version is probably the issue in internal implementation on Apple side and comparison with the ASCII code table, where the codes of these characters (,,-,.,/) are in order (from 44 to 47)
This is probably a part of their algorithm.
If you want the formatter to return nil in this case you can change the dateFormat to:
dateFormatter.dateFormat = "yyyy/MM/dd"
Results
let date = dateFormatter.date(from: "2020/////07////////10") // nil
let date2 = dateFormatter.date(from: "2020/07/10") // Jul 10, 2020 at 12:00 AM"
let date3 = dateFormatter.date(from: "2020.07.10") // Jul 10, 2020 at 12:00 AM"
I did run your code and it gives nil
Whereas if I enter correct date format then I receive the output
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020-7-10")
print(date) // Optional(2020-07-10 00:00:00 +0000)

GMT date string getting converted to UTC Date

**
GET GMT DATE STRING
**
func getGMTString(dateAsDate:NSDate) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"//this your string date format
// dateFormatter.locale = NSLocale.currentLocale()
// dateFormatter.timeZone = NSTimeZone(name: "GMT")
let date = dateFormatter.stringFromDate(dateAsDate)
return date
}
OUTPUT
startDate---2016-06-29 00:00:00 GMT+5:30
endDate----2016-06-30 03:57:39 GMT+5:30
NOW TRYING to get GMT Date object from output string
func getGMTDate(string:String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"//this your string date format
// dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")!
// dateFormatter.locale = NSLocale.currentLocale()
let date = dateFormatter.dateFromString(string)
return date!
}
PROBLEM: OUTPUT DATE OBJECT MESS
startDateOBJECT---2016-06-28 18:30:00 +0000 endDateOBJECT----2016-06-30 17:30:00 +0000
Unable to figure what is going wrong
I don't understand your step 3. I looks like you're using NSLog or a Swift print to display the resulting date. That is ALWAYS done in UTC.
If you want to view your date in a different format, or with your local time zone, you need a second date formatter to convert the NSDate to an output date string.
Here's the flow:
input date string -> input date formatter -> NSDate
NSDate -> output date formatter -> display date in local time zone

Why can I not format my NSDate with the specified time zone with NSDateFormatter?

I want to get a date that is represented in a String with a time zone GMT+1 and display it on screen with the local time zone GMT+10.
I have 2 methods, one is for create a date from a String (with GMT+1 timeZone), the other one is to format the date into a String (with localTimeZone GMT+10):
func dateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+1")
dateFormatter.dateFormat = "M/d/yyyy hh:mma"
return dateFormatter.dateFromString(dateString)
}
func stringFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
return dateFormatter.stringFromDate(date)
}
In the playground, when I do this:
let date = dateFromString("4/8/2015 1:29am")!
println(date)
println(stringFromDate(date))
I get the following output on the right side:
"Apr 8, 2015, 1:29 AM"
"2015-04-07 15:29:00 +0000"
"1:29 AM"
I don't understand why I don't get what I am expecting and looking for:
"Apr 8, 2015, 1:29 AM"
"2015-04-08 10:29:00 +0000"
"10:29 AM"
What's wrong?
Input formatters need the time zone in their string. Like so:
func dateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yyyy hh:mma z"
return dateFormatter.dateFromString(dateString)
}
let date = dateFromString("4/8/2015 1:29am GMT+01")!
Also note that NSTimeZone names have a two digit offset. Compare in the playground
var oops = NSTimeZone(abbreviation: "GMT+1")
var righteous = NSTimeZone(abbreviation: "GMT+01")
The first is nil, the second is not.
I wouldn't trust the formatting of a time stamp that the debugger prints. In my experience dates are always in UTC regardless of the time zone you set according to the log. Try adding the date as a string to a label on the project and see if it's right.
The reasoning behind this as far as I know is that when you print to the log, all it's doing is calling -description. In the case of NSDate this will return in UTC by definition.

How to extract day, month and year (dd-MM-yyyy) from Date (2018-09-28 09:42:00 +0000 ) without time in Date format - iOS swift?

I want to get 2018-09-28 from 2018-09-28 09:42:00 +0000 in Date format. I
can extract the same in string format but I want to get this in Date format. Here is my sample code.
let date = Date(timeIntervalSince1970: (TimeInterval(timer/1000)))
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let myDate = df.string(from: date)
let updateDate = df.date(from: myDate)
//date - 2018-09-28
//updateDate - 2018-09-28 09:42:00 +0000
You can simply get your date string prefix 11 and insert noon time when parsing your string:
let str = "2018-09-28 09:42:00 +0000"
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"
if let date = df.date(from: str.prefix(11) + "12:00") {
print(date.description(with: .current))
}
// Friday, September 28, 2018 at 12:00:00 PM Brasilia Standard Time

Resources