Is there a way to get the dateFormat string automatically (without explicit setting it)?
///getting the date from datePicker
func handleDatePicker(sender: UIDatePicker) {
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale.currentLocale()
timeFormatter.dateStyle = .MediumStyle
timeFormatter.dateFormat = "dd MMM yyyy" ///get this automatically???
dateTextField.text = timeFormatter.stringFromDate(sender.date)
}
[...]///other stuff
let dateString = dateTextField.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy" //can I get the string automatically based on user locale??? so I don't have to worry about setting the correct string?
dateFormatter.locale = NSLocale.currentLocale()
let dateFromString = dateFormatter.dateFromString(dateString!)
print(dateFromString)/// gives nil if dateFormatter.dateFormat = "dd MMM yyyy" is commented out
You can able to use the following ways to apply the date format automatically. The below code is in Swift 3.0.
Way 1(Using Custom Date and Time Styles):
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "dd MMM yyyy", options: 0, locale: NSLocale.current)
let dateString = dateFormatter.string(from: Date())
Way 2(Using Preset):
let dateString = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .none)
Please refer this link for more info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.