Reputation: 255
I am having an issue with converting a string to NSDate in Xcode: I am trying to get the current date, subtract one day and set the hour to noon. This is how I'm going about it (thw two snippets are in different functions):
let date = NSDate();
let dateFormatter = NSDateFormatter()
//var locale = NSLocale(localeIdentifier: "en_US_POSIX")
//dateFormatter.locale = locale
dateFormatter.dateFormat = "dd/mm/yyyy HH:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
var string = dateFormatter.stringFromDate(date)
var localdate = dateFormatter.dateFromString(string)
var localString = dateFormatter.stringFromDate(localdate!)
var calendar = NSCalendar.currentCalendar()
var components = calendar.components(NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.YearCalendarUnit, fromDate: localdate!)
self.dateCriteriaHour = components.hour
self.dateCriteriaDay = components.day
self.dateCriteriaMonth = components.month
self.dateCriteriaYear = components.year
This seems to work: I get the current date's components. Then I do this:
var day = String(self.dateCriteriaDay - 1)
var month = String(currentMonth)
var year = String(self.dateCriteriaYear)
var hour = "12:00"
var date = year + "/" + month + "/" + day + " " + hour
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/m/dd HH:mm"
var criteriaDate = dateFormatter.dateFromString(date)
println(date)
println(NSDate())
println(criteriaDate)
This is where things get strange. Here is the output to the console:
2015/7/11 12:00
2015-07-12 15:21:42 +0000
Optional(2015-01-11 04:00:00 +0000)
I understand that the device stores time in its selected time zone so I'm not too worried about that. What puzzles me is basically that everything is right except for the month, even though it comes out right in the string.
Any idea as to why this is happening?
Upvotes: 0
Views: 151
Reputation: 90117
Your dateformat is wrong.
dd/mm/yyyy HH:mm
^^ ^^
You use mm
two times. A lower case m
means minutes, an upper case M
means month. So your dateFormat should be dd/MM/yyyy HH:mm
Upvotes: 2