如何比较时间 [英] How to compare time

查看:114
本文介绍了如何比较时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较目标C的时间?

How to compare time in Objective C?

if (nowTime > 9:00 PM) && (nowTime < 7:00 AM) 
{
  doSomething;
}


推荐答案

当前小时并将其与某些时间进行比较,您将必须使用 NSDate NSDateComponents NSCalendar

If you want to get the current hour and compare it to some times, you're going to have to use NSDate, NSDateComponents, and NSCalendar.

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];

if (currentHour < 7 || (currentHour > 21 || currentHour == 21 && (currentMinute > 0 || currentSecond > 0))) {
    // Do Something
}

这将检查时间是否在9:00 PM和7:00 AM。当然,如果你想要不同的时间,你将不得不改变代码一点。

That will check if the time is between 9:00 PM and 7:00 AM. Of course, if you're going to want different times you'll have to change the code a little.

阅读关于 NSDate NSDateComponents NSCalendar 了解详情。

Read about NSDate, NSDateComponents, and NSCalendar to learn more.

这篇关于如何比较时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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