Swift 使字符串中的 NSDate 无法按预期工作 [英] Swift make NSDate from string not working as expected

查看:64
本文介绍了Swift 使字符串中的 NSDate 无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期字符串转换为 NSDate.我有这个输入日期字符串 2014-10-09 17:57 和这个时区 +4Asia/Dubai 出于某种原因,我在我执行 2014-10-09 13:57:00 +0000 下面的代码后得到这个 NSDate.

I'm trying to convert a date string into a NSDate. I have this input date string 2014-10-09 17:57 and this timezone +4 or Asia/Dubai and for some reason, i get this NSDate after i execute the code below 2014-10-09 13:57:00 +0000.

let dateString = "2014-10-09 17:57"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
formatter.timeZone = NSTimeZone(name: "Asia/Dubai")
println("\(formatter.dateFromString(dateString))")

我想要一个这样的日期 2014-10-09 17:57 +0400.我究竟做错了什么?你能帮我弄清楚吗?我需要日期来在这个和另一个用时区正确格式化的日期之间进行一些计算.

I want to get a date like this 2014-10-09 17:57 +0400. What am i doing wrong? Can you help me figure it out? I need the date to make some calculations between this one and another one which is correctly formatted with timezone.

推荐答案

它有助于分解复合语句.格式化程序的结果是一个日期,从参考日期 (GMT) 算起的秒数,它没有格式或时区的概念.

It helps to breakup compound statements. The result of the formatter is a date, seconds since the reference date (GMT), it has no concept of a format or timezone.

println() 显示基于日期的离子以及那里描述方法的默认格式.

The println() displays the date based ion the default formatting of there description method.

如果您希望它以特定方式显示,请使用日期格式化程序来创建所需的字符串表示.

If you want it display in a particular way use a date formatter to create the desired string representation.

示例:

let dateString = "2014-10-09 17:57"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
formatter.timeZone = NSTimeZone(name: "Asia/Dubai")
let date = formatter.dateFromString(dateString)
println("date: \(date!)") // date: 2014-10-09 13:57:00 +0000

formatter.dateFormat = "yyyy-MM-dd HH:mm Z"
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)") // formattedDateString: 2014-10-09 17:57 +0400

这篇关于Swift 使字符串中的 NSDate 无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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