Convert datestring to Swift 3 NSDate [duplicate] - ios

This question already has an answer here:
How to format DateFormatter(NSDateFormattter) for Date String
(1 answer)
Closed 5 years ago.
I having a date string:
Wed Mar 25 2017 05:30:00 GMT+0530 (IST)
I want to convert this string to the Date object in Swift 3.
I have referred to Link1, Link 2 and Link 3 for generating the format for this date string but could not get the correct format.

1) If you have string which contains timezone names like IST or GMT differences, then you can use NSDateDetector as explained in this SO post answer:
extension String {
var nsString: NSString { return self as NSString }
var length: Int { return nsString.length }
var nsRange: NSRange { return NSRange(location: 0, length: length) }
var detectDates: [Date]? {
return try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
.matches(in: self, range: nsRange)
.flatMap{$0.date}
}
}
//your example here
let dateString = "Wed Mar 25 2017 05:30:00 GMT+0530 (IST)"
if let dateDetected = dateString.detectDates?.first {
let date = dateDetected//Mar 25, 2017, 5:30 AM
print(dateDetected)//2017-03-25 00:00:00 +0000 - this is GMT time
}
Mar 25, 2017, 5:30 AM //date converted to local time zone
2017-03-25 00:00:00 +0000 //printed value of GMT time
2) Or if you some how able to remove GMT and IST reference from your string then try this:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, MMM d yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Wed Mar 25 2017 05:30:00 +0530")!
print(date)
It will give you
Mar 25, 2017, 5:30 AM //date converted to local time zone
2017-03-25 00:00:00 +0000 //printed value of GMT time

var dateString = "Wed, 25 Mar 2017 05:30:00 +0000"
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
var dateFromString = dateFormatter.date(from: dateString)
print(dateFromString)

Related

Swift string convert to SwiftDate

How can I convert 12 Oct 2018 at 10:45:46 AM to SwiftDate DateInRegion?
My code returns nil:
let ds = "12 Oct 2018 at 10:45:46 AM"
let region = Region(tz: TimeZone.current,
cal: CalendarName.gregorian.calendar,
loc: Locale.init(identifier: "en"))
let format = DateFormat.custom("EEE, dd MM yyyy HH:mm:ss zzz")
var str = ds.date(format: format, fromRegion: region)
check your dateformat , is not available, the correct format is
let ds = "12 Oct 2018 at 10:45:46 AM"
let format = DateFormat.custom("dd MMM yyyy 'at' HH:mm:ss a")
for additional info you get old answered from SO.for dateformats you get detailed answer from here

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

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
}

Swift2: String to date, format it and back to string. Found nil

I have a date string: Sun, 07 Feb 2016 21:16:21 +0000
And need it in: dd.MM.yyyy
Following method throws fatal error: nil
if parsedElement == "date" {
if currentArticle.date.isEmpty {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let tempDate = dateFormatter.dateFromString(str)
dateFormatter.dateFormat = "dd.MM.yyyy"
let convertedDate = dateFormatter.stringFromDate(tempDate!)
currentArticle.date = convertedDate
}
}
Debug:
str String "Sun, 07 Feb 2016 21:16:21 +0000"
tempDate NSDate? 2016-02-07 21:16:21 UTC 0xe41bc67eba500000​
convertedDate String "07.02.2016"
Looks great, but the moment I release "currentArticle.date = convertedDate"​ it says convertedDate​ = nil
Ideas?
PS: currentArticle.date == isEmpty
EDIT: The if loop runs 5 times.
If I give currentArticle.date = str (only the date string), this is what the debugger says:
1. str String "Sun, 07 Feb 2016 21:16:21 +0000"
2. str ""
3. str String "Thu, 04 Feb 2016 21:18:34 +0000"
4. str ""
5. str String "Thu, 04 Feb 2016 18:57:14 +0000"
You're getting the fatal error:
unexpectedly found nil while unwrapping an Optional value -> tempDate
I assume you're getting this error in the line:
let convertedDate = dateFormatter.stringFromDate(tempDate!)
This is because you're force unwrapping an optional which is equal to nil. You should use optional binding to unwrap it, i.e.:
if let tempDate = tempDate {
let convertedDate = dateFormatter.stringFromDate(tempDate)
currentArticle.date = convertedDate
}
Now the question of why your date formatter is not returning a value for str in this instance is all to do with your data. You can add an else to the above optional binding code block to display str in this instance to narrow down the problem.

Swift get Last-Modified property from NSHTTPURLResponse as NSDate

I m trying to get the last-modified property of my URLResponse as NSDate.
I followed the instructions from:
How can I convert string date to NSDate?
Convert String to NSDate in Swift
Date string to NSDate swift
From String to NSDate in Swift
but none of them worked.. I receive the date properly as a String from the URLResponse-Object in the form of "Mon, 19 Oct 2015 05:57:12 GMT"
I need to convert this String to NSDate to be able to compare it with a localDate in the form of NSDate: 2015-10-19 05:57:12 UTC
I have also tried different dateFormats but it didn't make any difference.
my current code is as follows:
//The serverDate needs to match the localDate which is a
//NSDate? with value: 2015-10-19 05:57:12 UTC
if let httpResp: NSHTTPURLResponse = response as? NSHTTPURLResponse {
let date = httpResp.allHeaderFields["Last-Modified"] as! String //EXAMPLE: "Mon, 19 Oct 2015 05:57:12 GMT"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let serverDate = dateFormatter.dateFromString(date) as NSDate?
//conversion always fails serverDate == nil
println("ServerDate: \(serverDate)")
}
Can anyone explain why the conversion is failing? Is there any other approach I could try to convert my Date?
Swift 4, XCode 9:
let date = httpResponse.allHeaderFields["Date"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, dd LLL yyyy HH:mm:ss zzz"
let serverDate = dateFormatter.date(from: date)
The change to 'HH' suggested by #MikeTaverne is indeed required.
I solved it...
It was a logical Problem, since I wanted to parse a String for a Date i have to specify the input dateFormat to receive an proper Date back:
Input from Server: String = "Mon, 19 Oct 2015 05:57:12 GMT"
Which is a Date in the format: "EEEE, dd LLL yyyy HH:mm:ss zzz" (http://userguide.icu-project.org/formatparse/datetime)
--> working code:
if let httpResp: NSHTTPURLResponse = response as? NSHTTPURLResponse {
//EXAMPLE: "Mon, 19 Oct 2015 05:57:12 GMT"
let date = httpResp.allHeaderFields["Last-Modified"] as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, dd LLL yyyy HH:mm:ss zzz"
serverDate = dateFormatter.dateFromString(date) as NSDate?
//serverDate is now: 2015-10-19 05:57:12 UTC
println("ServerDate: \(serverDate)")
}
Like a comment said, this code works:
if let httpResp: NSHTTPURLResponse = response as? NSHTTPURLResponse {
// "Mon, 19 Oct 2015 05:57:12 GMT"
let headerDate = httpResp.allHeaderFields["Last-Modified"] as! String;
// converter
let dateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "EEEE, dd LLL yyyy HH:mm:ss zzz";
// your answer
let serverDate = dateFormatter.dateFromString(headerDate) as NSDate?;
print("ServerDate: \(serverDate)")
}
Note the capital HHinstead of hh from the accepted answer.

Format internet time string (Swift 1.2)

I'm trying to format a string from internet time to something more readable.
The input I have is something like: Mon, 27 Apr 2015 20:00:00 +0000
And I'd like to format it into just: Mon, 27 Apr
I'm fairly new to Swift so I don't know the best way to do this.
something like:
let unformattedDateString = "Mon, 27 Apr 2015 20:00:00 +0000"
let dateFormatter = NSDateFormatter()
// input format
dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
// create NSDate from String
let date = dateFormatter.dateFromString(unformattedDateString)!
// output format
dateFormatter.dateFormat = "E, dd MMM"
// create String from NSDate
let formattedDateString = dateFormatter.stringFromDate(date)

Resources