I'm working with some JSON data that returns a dateTime in this format: "2015-01-17T20:00Z", when I attempt to turn this into an NSDate object, I'm always left with nil. I've read through several of the tutorials and answers here on SO, Apple's NSDate / NSDateFormatter / Date Formatting docs, and pinged a few IRC channels.
Can anyone tell me what I'm doing wrong and a possible work around?
My failing code in a Swift playground:
let dateString = "2015-01-17T20:00Z"
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-ddThh:mmZ"
let d = dateStringFormatter.dateFromString(dateString)
println(d)
Output: "Optional(2015-01-17 06:00:00 +0000)"
Working code in the same Swift playground:
let dateString = "2015-01-17"
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
let d = dateStringFormatter.dateFromString(dateString)
println(d)
Output: "nil"
You have to format it like this "yyyy-MM-dd\'T\'HH:mmZ". You can try it also with this extension:
extension String {
func toDateFormattedWith(format:String)-> NSDate {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.dateFromString(self)!
}
}
as mentioned by rmaddy your date is UTC format so we will escape only the "T" as follow:
"2015-01-17T20:00Z".toDateFormattedWith("yyyy-MM-dd\'T\'HH:mmZ") // "Jan 17, 2015, 6:00 PM"
If you need some reference formatting your dates you can use this one;
Related
I am puzzled. I read the international spec for formats...yet it seems to return a nil in playgrounds and in code.
let dateString = "022018"
let formatter = NSDateFormatter()
formatter.setLocalizedDateFormatFromTemplate("MMyyyy")
let date = formatter.dateFromString(dateString)
I can't change the stringDate to be 02/2018...I have to maintain that format..what is the right mask then to get some output?
The problem is the call to formatter.setLocalizedDateFormatFromTemplate. I don't think this means what you think it does. You are turning a string to a date, not a date to a string. Just set the formatter's dateFormat. This works fine (Swift 3, hope you don't mind):
let dateString = "022018"
let formatter = DateFormatter()
formatter.dateFormat = "MMyyyy"
let date = formatter.date(from:dateString)
I copied an extension for Swift's Date object somewhere that allows me to initialize a Date from a string as follows:
extension Date {
init(fromString: String) {
let str = "\(fromString) 12:00"
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd hh:mm"
dateStringFormatter.timeZone = NSTimeZone.default
let d = dateStringFormatter.date(from: str)!
self.init(timeInterval: 0, since: d)
}
}
If, for instance, I pass "2016-10-16" as string for the custom initializer, the Date, when printed, should be "2016-10-16 22:00:00 +0000", but right now it is: "2016-10-15 22:00:00 +0000".
Any idea why?
Thanks!
Resolved the issue thanks to #jcaron.
Problem
The problem was that I mixed up 12 and 24 hour fomat when doing "hh:mm". This is used for 12-hour formats while I wanted to use the 24-hour format.
Solution
To solve that, "hh:mm" needs to be changed to "HH:mm"
I receive dates as String like this one:
"2016-05-20T12:25:00.0"
I want to get its corresponding NSDate object, and I'm trying this way:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDThh:mm:ss.s"
let date = dateFormatter.dateFromString(dateStr)
where dateStr is like the example I wrote first. I took the dateFormat string from this page, but I get a nil date, what is wrong there?
Thanks in advance
You have a few problems with your date format. First Y is for weekOfYear, D is for day of year. hh is used for 12 hours format, decimal second you should use capital S and you need to escape the 'T'
You should do as follow:
let dateString = "2016-05-20T12:25:00.0"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.dateFromString(dateString) {
print(dateFormatter.stringFromDate(date) ) // "2016-05-20T12:25:00.0\n"
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.stringFromDate(NSDate()) {
print(dateFormatter.stringFromDate(date) )
}
I've got a date stored in my database and I want to retrieve it and display it nicely in my tableview cells.
The format it comes in from the database and stored in option1 is BO05151530
Where the first two letters have meaning in the program but are not needed for the date so I take those off using the substringFromIndex function.
So what is left is 05151530 where it represents MMddhmm
I would like to display it nicely like MM-dd # h:mm a
For example 12-05 # 3:45 am
Here is what I tried but unfortunately ns_date1 comes up as nil each time.
What would you suggest I do?
let date1 = option1.substringFromIndex(option1.startIndex.advancedBy(2))
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMddhhmm"
let ns_date1 = dateFormatter.dateFromString(date1)
Try this. you don't need to separate BO NSDateFormatter can handle extra string
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "'BO'MMddHHmm"
let ns_date1 = dateFormatter.dateFromString("BO05151530")
dateFormatter.dateFormat = "'BO' MM-dd # hh':'mm a"
let string = dateFormatter.stringFromDate(ns_date1!)
try
dateFormatter.dateFormat = "MMddHHmm"
HH is 24 hour format and hh is 12 hour format. you need the 24 one
Check out this app, this will help you know the right format and give you code
https://itunes.apple.com/ae/app/date-format-creator/id965645209?mt=12
NOTE: you need to add year to get a correct NSDate
I have this function :
class func getTheDateString(stringForInputDate: String, fromFormat inputFormat: String, toFormat outputFormat: String) -> String {
let formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = inputFormat
formatter.timeZone = NSTimeZone.localTimeZone()
let dateForInput: NSDate = formatter.dateFromString(stringForInputDate)!
formatter.dateFormat = outputFormat
return formatter.stringFromDate(dateForInput)
}
and used it as:
let stringDate : String = "0515930" // "05151530"
if stringDate.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) < 8 {
print([ViewControllerForScreen1 .getTheDateString(stringDate, fromFormat: "MMddHmm", toFormat: "MM-dd # h:mm a")]);
}else {
print([ViewControllerForScreen1 .getTheDateString(stringDate, fromFormat: "MMddHHmm", toFormat: "MM-dd # h:mm a")]);
}
OUTPUT:
["05-15 # 9:30 AM"]
["05-15 # 3:30 PM"]
I really need your help guys. The following piece of code works fine in a Swift Playgound and with any iOS8 or 8.1 simulator. But with iOS7 and 7.1, the NSDate object is always set to nil.
The object dateString contains a JSON string (ISO 8601 format) like 2015-02-28T20:15:00+0100
I'm trying to convert this date string into a NSDate object with the following code :
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.ZZZ"
if let dateString = (json as NSDictionary).valueForKey("dateAndTime") as? String
{
let dateObject = dateFormatter.dateFromString(dateString)
}
Where's my mistake ? I'm getting confused!
Many thanks
The problem is with your time zone offset, your date format is not proper for that. Use the following format,
"yyyy-MM-dd'T'HH:mm:ssZZZZZ"