判断两个日期是不是同一天的几种方法(swift3新增了一种方法)

82 篇文章 1 订阅
2 篇文章 0 订阅

1,格式化成字符串比较

下面方法将两个日期格式化成只包含年月日的字符串,再比较两个字符串是否相等。
1
2
3
4
5
6
7
8
9
10
//初始化日期格式器
let  dformatter =  DateFormatter ()
dformatter.dateFormat =  "yyyyMMdd"
 
//开始比较
if  dformatter.string(from: date1) == dformatter.string(from: date2) {
     print ( "它们是同一天" )
} else  {
     print ( "它们不是同一天" )
}

2,取出日期的年、月、日部分,分别进行比较

1
2
3
4
5
6
7
8
9
10
let  calendar =  Calendar .current
let  comp1 = calendar.dateComponents([.year,.month,.day], from: date1)
let  comp2 = calendar.dateComponents([.year,.month,.day], from: date2)
 
//开始比较
if  comp1.year == comp2.year && comp1.month == comp2.month && comp1.day == comp2.day {
     print ( "它们是同一天" )
} else  {
     print ( "它们不是同一天" )
}

3,使用Calendar的isDate方法进行判断(推荐)

这个是  Swift3  新增的方法,使用方便,效率也最高。
1
2
3
4
5
if  Calendar .current.isDate(date1, inSameDayAs: date2) {
     print ( "它们是同一天" )
} else  {
     print ( "它们不是同一天" )
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值