SwiftDate:Swift中的日期处理库

SwiftDate是Github上开源的,使用Swift语言编写的NSDate封装库,可以很方便的在Swift中处理日期,比如日期创建,比较,输出等。

特性

  • 支持数学运算符进行日期计算(比如myDate + 2.week + 1.hour)
  • 支持比较运算符(比如<,>,==,<=,>=)
  • 快速获取/修改日期各部分内容(比如获取或修改日期中的月份)
  • 提供通用格式化输出或自定义的格式化输出
  • 提供一系列.toString方法
  • 提供简便的方法获取yesterday,tomorrow等

依赖

  • iOS 8.0+ / Mac OS X 10.10+
  • Xcode 6.3+
  • Swift 1.2

支持Swift2.0版本,地址在文末的Github段落中

使用

CocoaPods安装SwiftDate

我们需要通过CocoaPods安装SwitDate,如果你还没有安装cocoapods,可以通过如下命令安装

$ gem install cocoapods

然后在你的Xcode项目中的Podfile文件中,添加如下内容:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'SwiftDate'

最后,执行如下命令安装

$ pod install

创建日期

  • 通过解析字符串创建
let date_custom = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))

  • 通过指定日期各部分创建
let date_from_components = NSDate.date(refDate: nil, year: 2014, month: 01, day: nil, hour: nil, minute: nil, second: nil, tz: "UTC")
  • 通过String类的toDate方法创建
let date = "2015-07-26".toDate(formatString: "YYYY-MM-DD")
  • 通过NSDate的静态方法创建
let todayDate = NSDate.today()
let yesterdayDate = NSDate.yesterday()
let tomorrowDate = NSDate.tomorrow()

获取日期中年月日等信息

我们可以通过NSDate的以下属性获取

.year
.month
.weekOfMonth
.weekday
.weekdayOrdinal
.day
.hour
.minute
.second
.era
.firstDayOfWeek // (first day of the week of passed date)
.lastDayOfWeek // (last day of the week of passed date)
.nearestHour // (nearest hour of the passed date)
.isLeapYear() // true if date's represented year is leap
.monthDays() // return the number of days in date's represented month

修改日期

var date = NSDate()
date = date.set("hour",value: 12)!
date = date.set("day",value: 1)!

日期运算

let date = NSDate()
let tomorrow = date+1.day
let two_months_ago = date-2.months

时区转换

let date = NSDate() //本地时区
let date_as_utc = date.toUTC() //UTC 时间
let date_as_beijing = date_as_utc.toTimezone("UTC+8") //北京时间

日期比较

我们可以通过数学运算符比较

let date1 = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))
let date2 = NSDate.date(fromString: "2015-07-27", format: DateFormat.Custom("YYYY-MM-DD"))

if date2 > date1 {

  // TODO something

}

还可以通过NSDate的以下一些方法来比较

let isInRange : Bool = date1.isInTimeRange("11:00","15:00")
.isToday()  // true if represented date is today
.isTomorrow()
.isYesterday()
.isThisWeek() // true if represented date's week is the current week
.isSameWeekOf(date: NSDate) // true if two dates share the same year's week
.dateAtWeekStart() // return the date where current's date week starts
.beginningOfDay() // return the same date of the sender with time set to 00:00:00
.endOfDay() // return the same date of the sender with time set to 23:59:59
.beginningOfMonth() // return the date which represent the first day of the sender date's month
.endOfMonth() // return the date which represent the last day of the sender date's month
.beginningOfYear() // return the date which represent the first day of the sender date's year
.endOfYear() // return the date which represent the last day of the sender date's year
.isWeekday() // true if current sender date is a week day
.isWeekend() // true if current sender date is a weekend day (sat/sun)

NSDate转换为字符串

let string = date.toString(format: DateFormat.Custom("YYYY-MM-DD"))

也可以在转换方法中指定NSDateFormatterStyle

let string = date.toString(dateStyle: .ShortStyle timeStyle:.LongStyle relativeDate:true)

还可以通过以下方法转换为特定的字符串

.toISOString() //  DateFormat.ISO8601
.toShortString() // short style, both time and date are printed
.toMediumString() // medium style, both time and date are printed
.toLongString() // full style, both time and date are printed
.toShortDateString() // short style, print only date
.toShortTimeString() // short style, print only time
.toMediumDateString() // medium style, print only date
.toMediumTimeString() // medium style, print only time
.toLongDateString() // long style, print only date
.toLongTimeString() // long style, print only time

最后我们还可以输出相对时间的格式,比如输出"2 hours ago"

var d = NSDate()-2.hour
var abb = d.toRelativeString(abbreviated: true, maxUnits: 3)
println("data: \(abb)")

Github

SwiftDate
SwiftDate支持Swift 2.0版本

本文作者: 阳春面
原文地址:http://www.aswifter.com/2015/07/26/use-swiftdate/

欢迎关注我的微信公众号,分享Android 开发,IOS开发,Swift开发和互联网内容
微信号:APP开发者

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 有一个rapper写过一个rap,词是这么写的:天干物燥,小心火烛,人生漫长,我劝你好生走路。这是我很喜欢的一句话...
    爱在樱花雨纷飞阅读 199评论 0 0
  • 梦中安排了 好多次机缘 却总越不过沉默 的门槛 太阳叮叮铛挡 敲着调色板 没有小雨 我却把自己 站成一把小伞 将织...
    微雨凭栏阅读 193评论 0 1
  • 中午本来想小睡一会,结果做了一个梦再起来已经过去一个小时了,很奇怪,在梦里知道自己在做梦,因为梦见自己回到了曾经在...
    Yw文哪儿阅读 228评论 0 4
  • 胡理乐 “快点,先把作业做完!”孩子放学刚进家门,妈妈就命令道。 “妈妈,我想先玩一会再做作业。”孩子试着与妈妈协...
    快乐爸爸日记阅读 7,678评论 1 6