错误地将String转换为NSDate [英] Bad converting String to NSDate

查看:105
本文介绍了错误地将String转换为NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将String转换为NSDate时遇到问题。在我的文本字段中,当用户点击它时,可以使用 UIDatePicker 选择日期。 String 作为中的日期TextField 看起来像这样:yyyy-mm-dd现在当我尝试转换日期时例如在2016-05-13使用此方法:

I have a problem with converting String to NSDate. In my text field when user tap on it, is a possibility to chose a date using UIDatePicker. String as a date in TextField looks like that: "yyyy-mm-dd" Now when I try to convert date for example on 2016-05-13 using this method:

func changeStringToNSDate(){

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let from = moreSorts.fromDatePickerTextField.text!
let fromDate = dateFormatter.dateFromString(from)

print(fromDate)

}

当我打印 fromDate 时,我收到 fromDate 的信息是不是2016-05-13而是2016-01-11 23:58:00 +0000。我不知道为什么我有2016-01-11在我的 TextField 字符串显示2016-05-13

When I print fromDateI recieve an information that fromDate is not 2016-05-13 but 2016-01-11 23:58:00 +0000. I don't know why I have 2016-01-11 when in my TextField String shows 2016-05-13

推荐答案

使用您提供的信息很难确定可能出现的问题。在Swift游乐场我得到2016-01-13而不是2016-01-11,但是如果我改变日期格式,我可以得到2016-05-13:

It's difficult to tell what might be going wrong for sure with the information you've provided. In a Swift playground I'm getting 2016-01-13 and not 2016-01-11, but if I change the date format, I can get 2016-05-13:

dateFormatter.dateFormat = "yyyy-MM-dd"

大写MM是关键。我会查看这个网站,以了解日期格式选项:

The uppercase MM is key. I would check out this website to play around with the date format options:

http ://nsdateformatter.com

这篇关于错误地将String转换为NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆