简体   繁体   中英

compare string date to current date

Hello i have a problem i have a value(date value) from server and i have to check that value with current date and to see which one is greater .i am using the following code but it also shows second date is greater ..how to solve this.It always come to else block.

NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSDate *dateOfEvent=[dateFormatter dateFromString:@"2013-04-04 03:22:55"];


if([dateOfEvent compare:[NSDate date]]==NSOrderedAscending)
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Message" message:@"Event has    been passed." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
    return;
}
else
{

   }

You are not creating the date properly, the formatter has to have the same format as the string. If your string is "2013-04-04", then your date formatter should be "yyyy-MM-dd:

NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSDate *dateOfEvent=[dateFormatter dateFromString:@"2013-04-04"];

Convert both dates in same format. Then compare as follows:

if (serverDate.timeIntervalSince1970 > currentDate.timeIntervalSince1970) {
// Server date is greater. Do your stuff

}
else {
// Current date is greater. Do your stuff
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM