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)
Related
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)
I've a specific time format which I want to use to generate a Date object.
This is the format:
Fri, 17 Mar 2017 08:42:00 +0100
Here is my Swift code that should create the data object:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss xx"
let d = dateFormatter.date(from: value)
The generation of the Date object with dateFormatter.date does always return nil. But I cant see what's wrong in my formatting string.
Can anyone see my error?
I have test it and works perfectly.
Could you test this code line to identify you Locale configuration?
print(Locale.current.identifier)
I only made a little change related to the Optional result that DateFormatter method returns
import Foundation
let the_date: String = "Fri, 17 Mar 2017 08:42:00 +0100"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss xx"
if let d = dateFormatter.date(from: the_date)
{
print(d)
}
I have this code working but now all of a sudden, it started crashing. I could not figure it out, any help would be appreciated.
let dateFormatter = NSDateFormatter()
dateFormat = "EEE, MMM d, yyyy hh:mm a"
dateFormatter.dateFormat = dateFormat
let date = dateFormatter.dateFromString("Thu, Jan 5, 2017 12:28 PM")
It is returning date as nil. Why? I want it to return proper date.
This looks like a possible duplicate question, but it is with specific details.
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "EEE, MMM d, yyyy hh:mm a"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt = "Thu, Jan 5, 2017 12:28 PM"
let dt1 = dateformattor.dateFromString(dt as String)
print(dt1) //print date and time UTC format.
Output :
2017-01-05 06:58:00 +0000
var dateFormatter = DateFormatter()
let dateFormat = "EEE, MMM d, yyyy hh:mm a"
dateFormatter.dateFormat = dateFormat
let date = dateFormatter.date(from: "Thu, Jan 5, 2017 12:28 PM")
OUTPUT :
Every time you work with time and date formatters remember to set locale and timezone!
Device with non-english locale will fail to parse "Thu, Jan 5, 2017 12:28 PM" as "Thu" and "Jan" are obviously english specific.
So:
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
or whatever time zone and locale you want to use
In iOS, I am using a NSDateFormatter with the DateFormat EEE, dd MMM yyyy HH:mm:ss z.
The String Sat, 29 Aug 2015 12:34:36 EDT does not work and gives back nil when given to the function .dateFromString(). The exact same string with GMT (Sat, 29 Aug 2015 12:34:36 GMT) gives me the correct date, though.
What am I missing here?
So the problem was that the locale I was using wasn't a usual one. I live in Germany and use English as my system language, so the Locale was one with the identifier en_DE. Both de_DE and en_US work with the usual Time Zones (Like EDT), but the unusual en_DE doesn't work with all of them. So the fix was to use en_US as the locale.
Hopefully this should work, I'm in New Zealand but set locale to "EDT"
let string = "Sat, 29 Aug 2015 12:34:36 EDT"
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "EDT")
formatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss z"
let localDate = formatter.dateFromString(string)
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.