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

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.

Related

How to get the same output of departed Date.parse() in groovy?

I have an application that runs the old version of the spring application. The application has the function to create date objects using Date.parse as follows
Date getCstTimeZoneDateNow() {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def zonedDateString = new Date().format(dateFormat, TimeZone.getTimeZone('CST'))
Date date = Date.parse(dateFormat, zonedDateString)
return date // Tue Oct 18 20:36:12 EDT 2022 (in Date)
}
However, the code above is deprecated. I need to produce the same result.
I read other posts and it seems like Calender or SimpleDateFormatter is preferred.
And I thought SimpleDateFormatter has more capabilities.
This post helped me understand more about what is going on in the following code
SimpleDateFormat parse loses timezone
Date getCstTimeZoneDateNow() {
Date now = new Date()
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
SimpleDateFormat sdf = new SimpleDateFormat()
sdf.setTimeZone(TimeZone.getTimeZone('CST'))
// cstDateTime prints times in cst
String cstDateTime = sdf.format(now) // 2022-10-18T20:36:12.088Z (in String)
// JVM current time
Date date = sdf.parse(cstDateTime) // Tue Oct 18 21:36:12 EDT 2022 (in Date)
return date
}
Here my goal is to return the date object that is in the format of Tue Oct 18 20:36:12 EDT 2022
The format is good. However, like the post says, when I do sdf.parse(), it prints in JVM time.
This means, the format is good but the time zone is off.
How can I get the exact same result as before?
It does not have to use SimpleDateFormatter. Could be anything.
Thank you so much for reading and for your time.
Perhaps the important thing is, that the Date is always neutral to the timezone. Given example shows what is to be expected to work from the Java specs:
def format = new SimpleDateFormat()
format.setTimeZone(TimeZone.getTimeZone("CST"))
println new Date()
def date = format.parse(format.format(new Date()))
printf "parsed to %s%n", date
printf "formatted to %s (%s)%n", format.format(date), format.getTimeZone().getDisplayName()
In the output, notice when using the Format and when the toString(), a different time is shown accordingly, which is perfectly fine, since first we format and then parse again in the same format, thus the same time-zone. Later, we use the Date.toString() to output the date, this time using the system default time-zone which is always used when Date.toString() is called. In the output, the time-zone shift is reflected:
Thu Oct 20 09:22:58 EDT 2022
parsed to Thu Oct 20 09:22:00 EDT 2022
formatted to 10/20/22 8:22 AM (Central Standard Time)

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)

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

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"

Resources