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

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)
}

Related

How to get current time with offset in Java?

How do I get the current time in the below format. Timezone is Europe/London:-
04:47 PM GMT+1
I have tried various different ways, including below code:-
ZoneId zone = ZoneId.of("Europe/London");
Locale locale = Locale.forLanguageTag("en-GB");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"dd MMM uuuu HH:mm OOOO", locale);
ZonedDateTime dateTime = Instant.now().atZone(zone);
String result = dateTime.format(formatter);
This gets me -->30 Mar 2021 18:36 GMT+01:00. But its not what I want.
Update:- Its resolved now. This pattern helped----->> DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "hh:mm a O", locale);

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)

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

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"

(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