比较ios中的两个时间值? [英] Compare two time values in ios?

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

问题描述

在我的应用程序中,我想检查当前时间是否在变量中保存的时间之前或之后。

In my app i want to check whether the current time is before or after the time saved in a variable.

就像我的time1是 time1 = @08:15:12; 我的时间2是 time2 = @18:12:8;

like my time1 is time1=@"08:15:12"; and my time2 is time2=@"18:12:8";

所以我想在time1和time2之间进行比较。目前这些变量都是NSString格式。

so i wanna compare between time1 and time2.Currently these variables are in NSString Format.

以下是用于获取的代码时间,我不知道如何比较它们。

Following are the code used to get time,and i dont know how to compare them.

代码:

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"HH:MM:SS";
        [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
        NSLog(@"ewetwet%@",[dateFormatter stringFromDate:now]);

请帮帮我

推荐答案

使用以下代码进行从nsstring到nsdate的转换并比较它们。

Use the following code to do the convert from the nsstring to nsdate and compare them.

NSString *time1 = @"08:15:12";
NSString *time2 = @"18:12:08";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];

NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];

NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
    NSLog(@"date1 is later than date2"); 
}
else if(result == NSOrderedAscending)
{
    NSLog(@"date2 is later than date1"); 
}
else
{
    NSLog(@"date1 is equal to date2");
}

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

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