NSDate区域格式问题

时间:2012-01-06 21:30:10

标签: iphone nsdate nsdateformatter

NSDateFormatter *dtFormatter = [[NSDateFormatter alloc] init];
[dtFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];
NSDate *selectedDate = [[NSDate alloc] init];
        selectedDate = [dtFormatter dateFromString:[NSString stringWithFormat:@"%@",    [appDelegate.aryTime objectAtIndex:i]]];        
    NSLog(@"selected Date: %@", selectedDate);
    NSLog(@"Today Date: %@", todayDate);

    int interval = [todayDate compare:selectedDate];

我有这段代码。现在,当我运行应用程序保持英国的区域格式(来自设置>一般>国际>设置区域格式)(他们使用AM和PM)时,该应用比较两个日期。但是,如果我将我的区域格式更改为瑞典(他们使用em和fm代替),则不会比较日期。是否有任何方法可以删除区域格式的依赖关系并比较日期?我尝试用24小时格式转换它们,但这没有帮助。

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式比较两个日期..

==>扩展内置的NSDate类(.h以及.m文件)

#import <Foundation/Foundation.h>
struct DateInformation {
int day;
int month;
int year;
int weekday;
int minute;
int hour;
int second;
 };
  typedef struct DateInformation DateInformation;
  @interface NSDate (Extra)
   - (DateInformation) dateInformation;
   @end

实施班:

#import "NSDate+Extra.h"

  @implementation NSDate (Extra)

- (DateInformation) dateInformation
   {
DateInformation info;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit |NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) 
                                      fromDate:self];
info.day = [comp day];
info.month = [comp month];
info.year = [comp year];

info.hour = [comp hour];
info.minute = [comp minute];
info.second = [comp second];

info.weekday = [comp weekday];


[gregorian release];
return info;
    }

@end

来自您要与日期进行比较的班级

对两个日期执行以下操作

 NSDate *date=[NSDate date];
 DateInformation info=[date dateInformation];
   NSLog(@"%@",info);

 NSDate *date1=[NSDate dateWithTimeIntervalSinceNow:1242141];
 DateInformation info=[date1 dateInformation];
   NSLog(@"%@",info);

在扩展日期类中再实现一个方法,用于比较日期的所有参数,即整数..

希望它可以帮到你

的问候, 尼尔