Convert date string to NSDate - ios

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

Related

Issue when converting a date string of format "yyyy-MM-dd HH:mm:ss.m" to "yyyy-MM-dd HH:mm:ss"

I'm working on an iOS project in swift 5. In one of my API, the date is coming in the format, "yyyy-MM-dd HH:mm:ss.m". And from this date, I need to fetch the time. But the issue is, suppose the date I'm getting from API is "1900-01-01 08:30:00.000000", and when I convert this date format to YYYY-MM-dd HH:mm:ss, the result is coming as "1900-01-01 08:00:00", the time before conversion is 08:30:00.000000 but after conversion 08:00:00. Why it is happening? Please help me.
I will add my code here,
let dateTime = "1900-01-01 08:30:00.000000"
let outFormatter = DateFormatter()
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.m"
if let date = outFormatter.date(from: dateTime) {
//here value od date is 1900-01-01 04:18:48 +0000
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
outFormatter.locale = tempLocale
let exactDate = outFormatter.string(from: date)
//here the value of exactDate is 1900-01-01 08:00:00
}
m is minutes and S is milliseconds so the format must be "yyyy-MM-dd HH:mm:ss.S".
Further for fixed date formats it's highly recommended to set the locale to en_US_POSIX
let dateTime = "1900-01-01 08:30:00.000000"
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_US_POSIX")
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"
if let date = outFormatter.date(from: dateTime) {
//here value od date is 1900-01-01 04:18:48 +0000
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let exactDate = outFormatter.string(from: date)
//here the value of exactDate is 1900-01-01 08:00:00
}
But if you only want to strip the milliseconds from the date string there is a simpler solution
let dateTime = "1900-01-01 08:30:00.000000"
let exactDate = dateTime.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
It removes the dot and any digit behind

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

Swift how to convert string to NSDate

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

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.

Format string to NSdate in Swift

My string is = "2015-08-26 14:21:40.557"
My code:
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:Z"
var date = dateFormatter.dateFromString(creationDateStr as String )
I get a nil date , what's the right format?
The format must match your input string exactly, so
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
will do the job.
Note that Z is used for the timezone, not for (milli)seconds.
And HH is for 24 hours; hh only allows values between 01 and 12 and is usually paired with a to indicate AM/PM.
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var date = dateFormatter.dateFromString(creationDateStr as String )
Will return nil if your string is not in this date format. (ex. "5/26/2015" will return nil but "2015-05-26 12:30:00.123" will return a nsdate)
The format is incorrect for the string you are attempting to parse.
The correct format is:
"yyyy-MM-dd HH:mm:ss.SSS"
Parsing an incorrect format will return a nil value.
var str = "2015-08-26 14:21:40.557"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var date = dateFormatter.dateFromString(str)

Resources