Swift how to convert string to NSDate - ios

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"]

Related

Convert date string to NSDate

I've this string: "2016-10-08 00:20:00.000000". And I need it as an NSDate (Date for swift 3) object.
I've tried with the following:
let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd hh:mm:ss"
print(formatterJsonDate.date(from: "2016-10-08 00:20:00.000000"))
I always return nil value. What's wrong? I guess it's something about the date format.
Your date format and your time string should be same. In your case it should be like,
let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd HH:mm:ss"
print(formatterJsonDate.date(from: "2016-10-08 00:20:00"))
Or change dateformatter like,
"yyyy-MM-dd HH:mm:ss.SSSSSS"
And hh should be capital for 24 - hour format!!!! like HH!
If you want use nano seconds your code must be :
let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd hh:mm:ss.SSSS"
if let myDate = formatterJsonDate.date(from: "2016-10-08 00:20:00.000000") {
print(myDate)
} else {
print ("Invalid Date")
}

NSDate from string is always nil

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

How to convert a string to a date, without losing the formatting

I have this date 2015-11-06T18:00:00-0500
My format is yyyy-MM-dd'T'HH:mm:ssZ
i try
let startDateString = "2015-11-06T18:00:00-0500"
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let startDateBtnEnd = format.dateFromString(startDateString)
println("startDateBtnEnd 2 \(startDateBtnEnd)")
But the log is
startDateBtnEnd 2 Optional(2015-11-07 00:00:00 +0000)
NSDate stores dates in UTC. You can convert it to the same moment in time in any timezone. But after losing too many neurons to mentally convert NSDate from one timezone to another, I decided to add my own extension to NSDate to print it out in the local timezone instead:
extension NSDate {
func toString(timeZone: NSTimeZone = NSTimeZone.localTimeZone()) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.timeZone = timeZone
return formatter.stringFromDate(self)
}
}
// Usage:
print("startDateBtnEnd 2 \(startDateBtnEnd.toString())")

Format String to HH:mm in Swift

My code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString("2015-09-01 00-32-40")
Result: 2015-08-31 17:32:40
But I want get result like this: 17:32. How do I resolve it?
If you're trying to get an NSDate and not a string representation, printing the NSDate will always show the full date time. To just show the hours and minutes, you'll have to create a string representation using an "HH:mm" date format, ex:
// Your original code
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString("2015-09-01 00-32-40")
// To convert the date into an HH:mm format
dateFormatter.dateFormat = "HH:mm"
let dateString = dateFormatter.stringFromDate(date!)
println(dateString)
Not sure why you're looking to get a result of "17:32", but this will produce "00:32" as a result from the original "00-32" portion of the string.

How to constuct NSDate object from String with milliseconds

I need to construct NSDate object from String, so I wrote the following code:
func getNSDateObjectFromString(string: String) -> NSDate {
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.dateFromString(string)
return date!
}
Unfortunately, the input string sometimes may contain milliseconds too. What can I do in this case? I don't find any way to read milliseconds (not in the day) according to the http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
Thanks in advance.
As far as I know, the format doesn't support "optional" fields. So you have to try the formats one by one:
func getNSDateObjectFromString(string: String) -> NSDate {
var formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
var date = formatter.dateFromString(string)
if date == nil {
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
date = formatter.dateFromString(string)
}
return date!
}
You can try something like:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
A Swift 3 Solution
After a bit of trial and error with the date format this is what worked for me with Swift 3.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let date = formatter.date(from: "2017-03-11 13:16:31.177")!
debugPrint(dateFormatter.string(from: date))
and after a round trip results in the expected debug output of
"2017-03-11 13:16:31.177"
Note that using the format "yyyy-MM-dd'T'HH:mm:ss.SSS" resulted in formatter.date(from: returning a nil optional Date.
Are they important?
In DateFormatter you create your matching string in years, months, days, hours, mins, secs, but you don't need to. If your matching string does not contain any of them, formatter will just ignore them.

Resources