How to convert string to NSDate that has extraneous characters (swift)? - xcode

I have the string "Sat, 21 Nov 2015 19:20:48 EST\n\t\t\t" that I need convert to NSDate, but it gives me nil all the time.
I tried to clear the string by
dateString.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
result looks fine: Sat, 21 Nov 2015 19:20:48. Converting to NSDate = nil :(
Ok, I removed the noised characters manually and try to convert the string "Sat, 21 Nov 2015 19:20:48 EST" to NSDate. Nil again:
let dateString = "Sat, 21 Nov 2015 19:20:48 EST"
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: 'US_en')
formatter.dateFormat = 'yyyy-MM-dd'
print("date = \(date)")
//date = nil
What am I doing wrong?
Even if I use "formatter.timeZone = NSTimeZone(abbreviation: "EST")" still nil.

Answer to your first question:
You could use the following code to trim the unwanted whitespace and newlines from the string
var dateAsString = "Sat, 21 Nov 2015 19:20:48 EST\n\t\t"
dateAsString = dateAsString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
Answer to your second question:
Refer to the Date format symbols table in this link for list of all string formatting symbols.
You should be able to convert the specified date with this formatter,
let customDateFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
let date = dayTimePeriodFormatter.dateFromString(dateAsString) //"Sat, 21 Nov 2015 19:20:48 EST"

Related

Convert Date Time based on Locale

Hello I am new to FTL Code and I am trying to re format a date based on how a locale would display it.
The error I am getting: (Please look below for more info of the result we want)
The string doesn't match the expected date/time/date-time format. The string to parse was: "août 26, 2035". The expected format was: "MM dd, yyyy".
The nested reason given follows:
Unparseable date: "août 26, 2035"
<#assign locale = userPreferences.getLanguage()>
my locale ${locale}<br>
<#if locale = "en_AU">
original = ${couponData.expiration}<br>
<#assign expiryDate = couponData.expiration?date("dd MM, yyyy")?string("dd MM yyyy")>
format ${expiryDate} <br>
${sys.declare("dateMonthYear", expiryDate)}
<#elseif locale = "en_GB">
original = ${couponData.expiration}<br>
<#assign expiryDate = couponData.expiration?date("MM dd, yyyy")?string("dd MM yyyy")>
format ${expiryDate} <br>
${sys.declare("dateMonthYear", expiryDate)}
<#elseif locale = "fr_CA">
original = ${couponData.expiration}<br>
<#assign expiryDate = couponData.expiration?date("MMM dd, yyyy")?string("dd MM. yyyy")>
format ${expiryDate} <br>
${sys.declare("dateMonthYear", expiryDate)}
<#else>
${sys.declare("dateMonthYear", "${couponData.expiration}")}
</#if>
CA_FR Source:
Ends Jul 31, 2022
Actual:
Expire le juil. 31, 2022
Expected:
Expire le 31 juil. 2022
EN_GB Source:
Ends Jul 31, 2022.
Actual:
Ends Jul 31, 2022.
Expected:
Ends 31 Jul 2022.
enter code here
EN_AU Source:
Ends Jul 31, 2022.
Actual:
Ends 31 Jul, 2022.
Expected:
Ends 31 Jul 2022.
I was able to solve my issue:
it seems in the string MM-DD-YY will format into something like 01/01/2022
Where as was proving three MMM-DD-YYYY will give me Jan 01, 2022
I can manipulate the dateformat inside the string also
<#setting locale="fr">
<#assign expirationDate = expiration?number_to_date?string("yyyy MMM. dd")>

Swift 2: Parse RSS pubDate to NSDate object

I´m trying to convert a String (Date) from an RSS Feed ("pubDate") to an NSDate object in Swift 2.
let dateString:String = "Tue, 16 Aug 2016 15:27:33 +0000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.dateFromString(dateString)
print(date)
The problem is, that in that case the date object is always nil. The problem is the format of the input string. If I change dateString to "2016-08-16" then the NSDate object is built correctly.
So I´ve no idea how to get this NSDate working. String operations on the dateString before? Or some options on the dateFormatter?
Thanks for you help in advance!
While questions about how to convert from string to date is mostly about specifying the right format string, you should read what Apple has to say about NSDateFormatter and Internet Dates. The short version is that you should always specify the local as en_US_POSIX:
let dateString = "Tue, 16 Aug 2016 15:27:33 +0000"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
let date = dateFormatter.dateFromString(dateString)
print(date)

String from Date works, Date from String doesn't work

I'm taking a NSDate and turning it into a dateString. But then...
When I try to take that same dateString and turn it back into a NSDate my dates aren't correct.
NSDate to dateString...
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy H:mm a"
let dateString = dateFormatter.stringFromDate(timeDate as! NSDate)
print("Date: \(dateString)")
Console:
Date: Mar 22, 2016 22:30 PM
Date: Mar 23, 2016 1:00 AM
Date: Mar 23, 2016 9:00 AM
dateString to plainDate...
let reverseDateFormatter = NSDateFormatter()
reverseDateFormatter.dateFormat = "MMM d, yyyy H:mm a"
let plainDate = reverseDateFormatter.dateFromString(dateString)
print("Date Reverse: \(plainDate)")
Console:
Date Reverse: Optional(2016-03-22 17:30:00 +0000)
Date Reverse: Optional(2016-03-23 05:00:00 +0000)
Date Reverse: Optional(2016-03-23 05:00:00 +0000)
When your converting the Date to a string, your losing the timezone information, and then its not able to piece it back together.
Is there some reason you can't store the Date itself as an NSDate and then use that instead of re-building the date from a string?
If you need to convert it back to the full date from the string, you will need to adjust your format to store the timezone as well
stringFromDate returns a non-optional string, but dateFromString returns an optional date. Conditionally unwrap the result before printing it out:
if let result = reverseDateFormatter.dateFromString(dateString) {
print(result)
}

(Swift) Using NSDataFormatter with a medium style string to get date

I seem to be stuck here and I have been wasting way too much tome on this.
What I have is a string that is in the RFC 1123 format that I would like to get a date out of, but not matter what I do, I get a nil result;
let dateFormat = NSDateFormatter();
dateFormat.dateStyle = .MediumStyle;
dateFormat.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z";
dateFormat.locale = NSLocale.systemLocale();
dateFormat.timeZone = NSTimeZone(abbreviation:"GMT");
var currentDate = dateFormat.dateFromString("Sun, 28 Jun 2015 04:30:54 GMT");
I am not sure what I am missing, if I changed the MMM to MM and make Jun 06, then it works. It seems to be only this instance. I have tried moving the order of how dateFormat gets created, and still I get no results. Any help on this matter would greatly be appreciated
I think you have confused the formatter. You don't need to set anything except the format string, because the formatter's job is to learn those other settings from the string it reads.
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z"
var currentDate = dateFormat.dateFromString("Sun, 28 Jun 2015 04:30:54 GMT")
// "Jun 27, 2015, 11:30 PM"
If you do as above, it will return an NSDate? from the date string you provided.

I want convert from string to date

NSDate *LastBuildDate;
NSDate *PubDate;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyyMMddhhmmss"];
LastBuildDate = [formatter dateFromString:buttoninfoamtion.mLastdate];
PubDate=[formatter dateFromString:newsItem.mPubDate];
if([PubDate compare:LastBuildDate])
buttoninfomation.mlastdate and newsItem.mPubDate is string from OpenAPI
ex)
buttoninfomation.mlastdate: Tue, 18 Oct 2011 15:54:43 +0900
newspub:Tue, 18 Oct 2011 15:58:00 +0900
but
LastBuidDate = (null)
PubDate = (null)
I want to compare two factor .
So date- date or string- string but I think string - string is so complex.
what wrong up codes?
Well the format you've given of "yyyyMMddhhmmss" doesn't match "Tue, 18 Oct 2011 15:54:43 +0900" even slightly.
Try
EEE, dd MMM yyyy HH:mm:ss Z
as the format string - see the iOS documentation and the Unix TR#35 for more information.

Resources