Swift 日期格式 [英] Swift date formatting

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

问题描述

我正在尝试从按钮中提取日期字符串,格式是作为要存储在 CoreData 中的日期.

I'm trying to pull a date string from a button and format is as a date to be store in CoreData.

这是我的代码:

let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-YYYY"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!

如果我在 dateStr 上执行 println,我会得到以下信息:03-10-2015.然后,如果我立即在日期上打印,我会得到:2014-12-21 05:00:00 +0000.

If I do a println on dateStr I get the following: 03-10-2015. Then if I immediately println on date I get: 2014-12-21 05:00:00 +0000.

关于为什么当我通过日期格式化程序运行实际日期时实际日期发生变化的任何想法?

Any ideas as to why the actual date is changing when I run it through the date formatter?

推荐答案

NSDateFormatter 类参考:http://goo.gl/7fp9gl

NSDateFormatter Class Reference : http://goo.gl/7fp9gl

日期格式指南(Apple):http://goo.gl/8zRTQl

Date Formatting Guide (Apple) : http://goo.gl/8zRTQl

一个常见的错误是使用 YYYY.yyyy 指定日历年,而 YYYY 指定年份(一年中的一周"),用于 ISO 年-周日历.

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar.

你的代码应该像你期望的那样工作:

Your code should work, as you expect, like this :

let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!

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

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