在Objective-C中进行两次比较的最佳/最简单方法是什么? [英] What's the best/easiest way to compare two times in Objective-C?

查看:64
本文介绍了在Objective-C中进行两次比较的最佳/最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间的字符串表示形式,例如"11:13 AM".这是使用NSDateFormatter和stringFromDate:方法产生的.

I've got a string representation of a time, like "11:13 AM." This was produced using an NSDateFormatter and the stringFromDate: method.

我想将此时间与当前时间进行比较,但是当我使用dateFromString:方法将字符串转换回日期时,会添加年,月和日-这是我所不希望的.我只需要知道现在是否<或>存储在字符串中的时间.

I'd like to compare this time to the current time, but when I use the dateFromString: method to turn the string back into a date, a year, month and day are added - which I don't want. I just need to know if right now is < or > the time stored in the string.

处理该问题的最佳方法是什么?预先感谢您的帮助.

What's going to be the best way to handle that? Thanks in advance for your help.

推荐答案

而不是使用字符串表示形式,而是使用从选择器中获得的NSDate.您可以使用NSDateComponents转换时/分/秒,然后还可以将[NSDate日期]转换为NSDateComponents.比较两组组件的小时/分钟/秒.

Instead of using the string representation, use the NSDate you got from the picker. You can convert that hour/min/sec using NSDateComponents, then also convert [NSDate date] to NSDateComponents. Compare the hours/minutes/seconds of the two sets of components.

编辑-使用实用程序功能将NSDate的时/分/秒组件转换为secondsOfTheDay(自午夜以来的秒数).

EDIT -- use a utility function for things like this that converts the hr/min/sec components of NSDate into a secondsOfTheDay (seconds since midnight).

您可以直接使用一天中的两个时间值,因为它们都是自午夜以来的秒数.简单的整数可以轻松地进行比较,存储和操作.您不必一直使用NSDate.

You can directly use two time of day values since they are both seconds since midnight. Simple integers can be easily compared and stored and manipulated. You don't have to use NSDate all the time.

//----------------------------------------------------------------------------
// extracts hour/minutes/seconds from NSDate, converts to seconds since midnight
//----------------------------------------------------------------------------
unsigned secondOfTheDay( NSDate* time )
{
    NSCalendar* curCalendar = [NSCalendar currentCalendar];
    const unsigned units    = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents* comps = [curCalendar components:units fromDate:time];
    int hour = [comps hour];
    int min  = [comps minute];
    int sec  = [comps second];

    return ((hour * 60) + min) * 60 + sec;
}

这篇关于在Objective-C中进行两次比较的最佳/最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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