NSDateFormatter 返回错误的日期 + Swift [英] NSDateFormatter return wrong date + Swift

查看:68
本文介绍了NSDateFormatter 返回错误的日期 + Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

let dateString = "2016-04-02"
    var formatter: NSDateFormatter = NSDateFormatter()
    formatter.timeZone = NSTimeZone(abbreviation: "GMT +3:00")
    formatter.dateFormat = "yyyy-MM-dd"
    println("dateString: \(dateString)")
    formatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX")
    let date = formatter.dateFromString(dateString)
    println("date: \(date)")

    formatter.dateFormat = "yyyy-MM-dd"
    let formattedDateString = formatter.stringFromDate(date!)
    println("formattedDateString: \(formattedDateString)")

输出:

dateString: 2016-04-02
date: Optional(2016-04-01 21:00:00 +0000)
formattedDateString: 2016-04-02
2016-04-01 21:00:00 +0000

我正在尝试将字符串转换为 NSDate 数据类型,但没有获得正确的值.我尝试了很多解决方案,但没有返回正确的值.我需要 yyyy-MM-dd 格式(2016-04-02)与我输入的2016-04-02"相同的格式.如果有人可以提供帮助将是非常昂贵的.提前致谢

I am trying to convert a string to NSDate datatype but not getting correct value. I have tried many solutions but its not returning correct value. I need it in yyyy-MM-dd format (2016-04-02) same as my input "2016-04-02". If someone can help would be really apriciated. Thanks in advance

推荐答案

当你从字符串转换为 NSDate 时,如果你没有将时区设置为格式化程序,你将获得本地时区中某个日期的 NSDate.我想你的时区是 GMT+3 .

When you convert from string to NSDate, if you do not set the timezone to the formatter, you will get the NSDate of a date in your local time zone. I suppose that your time zone is GMT+3 .

然后,当您显示 'date' 的值(使用 println、NSLog 但不使用 NSDateFormatter)时,不设置时区,您将获得 GMT+0 时间.这就是为什么你迟到了 3 小时.

Then, when you show the value of 'date' (using println, NSLog but not NSDateFormatter), without setting the time zone, you will get GMT+0 time. That why you got 3h later.

取决于如何使用 NSDateFormatter,您将获得所需的日期字符串.在你的情况下,它返回你想要的,不是吗?

Depend on how to use NSDateFormatter, you will have the date string as you want. In your case, It returns what you want, doesn't it?

请记住,NSDate 表示时间.

Remember that NSDate presents a moment of time.

let dateString = "2016-04-02"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
println("dateString: \(dateString)")

formatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX")
let date = formatter.dateFromString(dateString) //without specify timezone, your dateString "2016-04-02" is your local time (GMT-3),  
//means it's 2016-04-02 00:00:000 at GMT+0. That is the value that NSDate holds.

println("date: \(date)") //that why it show 2016-04-01 21:00:000, but not 2016-04-02 00:00:000

formatter.dateFormat = "yyyy-MM-dd"
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)")

这篇关于NSDateFormatter 返回错误的日期 + Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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