查找 iPhone 中两个日期之间的总天数

发布于 2024-11-08 14:50:02 字数 430 浏览 0 评论 0原文

我想查找两个日期之间的总天数。

例如,今天是 01-01-2011(DD-MM-YYYY),第二个日期是 (25-03-2011),我如何找到总天数?

NSDate *currentdate=[NSDate date];
NSLog(@"curretdate is ==%@",currentdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:@"dd-mm-YYYY hh:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:@"20-04-2011 09:00:00"];

NSLog(@"toDate ==%@",toDate);

I would like to find total number of days between two dates.

e.g. today is 01-01-2011(DD-MM-YYYY) and second date is (25-03-2011), how would I find the total number of days?

NSDate *currentdate=[NSDate date];
NSLog(@"curretdate is ==%@",currentdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:@"dd-mm-YYYY hh:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:@"20-04-2011 09:00:00"];

NSLog(@"toDate ==%@",toDate);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

似梦非梦 2024-11-15 14:50:02

在您的日期格式中,您设置错误,它是 dd-MM-yyyy HH:mm:ss 。可能这就是问题所在..你得到了错误的日期并且没有得到答案我发送了一些代码来获取日期差异。

  NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
 [tempFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
  NSDate *startdate = [tempFormatter dateFromString:@"15-01-2011 09:00:00"];
  NSLog(@"startdate ==%@",startdate);

  NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
  [tempFormatter1 setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
  NSDate *toDate = [tempFormatter1 dateFromString:@"20-01-2011 09:00:00"];
  NSLog(@"toDate ==%@",toDate);

   int i = [startdate timeIntervalSince1970];
   int j = [toDate timeIntervalSince1970];

   double X = j-i;

   int days=(int)((double)X/(3600.0*24.00));
   NSLog(@"Total Days Between::%d",days);

编辑1:

我们可以使用以下函数找到日期差异:

-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
    // Manage Date Formation same for both dates
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [formatter dateFromString:date1];
    NSDate *endDate = [formatter dateFromString:date2];


    unsigned flags = NSDayCalendarUnit;
    NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

    int dayDiff = [difference day];

    return dayDiff;
}

来自 Abizern 的 ans。查找 NSDateComponent 的更多信息 <强>这里。

In your date Format tor u set wrong it`s be dd-MM-yyyy HH:mm:ss . may be that was the problem.. u get wrong date and not get answer i send litte bit code for get day diffrence.

  NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
 [tempFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
  NSDate *startdate = [tempFormatter dateFromString:@"15-01-2011 09:00:00"];
  NSLog(@"startdate ==%@",startdate);

  NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
  [tempFormatter1 setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
  NSDate *toDate = [tempFormatter1 dateFromString:@"20-01-2011 09:00:00"];
  NSLog(@"toDate ==%@",toDate);

   int i = [startdate timeIntervalSince1970];
   int j = [toDate timeIntervalSince1970];

   double X = j-i;

   int days=(int)((double)X/(3600.0*24.00));
   NSLog(@"Total Days Between::%d",days);

Edit 1:

we can find date difference using following function :

-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
    // Manage Date Formation same for both dates
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [formatter dateFromString:date1];
    NSDate *endDate = [formatter dateFromString:date2];


    unsigned flags = NSDayCalendarUnit;
    NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

    int dayDiff = [difference day];

    return dayDiff;
}

from Abizern`s ans. find more infromation for NSDateComponent here.

ゃ人海孤独症 2024-11-15 14:50:02
NSCalendar *Calander = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDateComponents *comps = [[NSDateComponents alloc] init];

[dateFormat setDateFormat:@"dd"];
[comps setDay:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:@"MM"];
[comps setMonth:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:@"yyyy"];
[comps setYear:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:@"HH"];
[comps setHour:05];
[dateFormat setDateFormat:@"mm"];
[comps setMinute:30];

NSDate *currentDate=[Calander dateFromComponents:comps];

NSLog(@"Current Date is :- '%@'",currentDate);


[dateFormat setDateFormat:@"dd"];
[comps setDay:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:@"MM"];
[comps setMonth:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:@"yyyy"];
[comps setYear:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:@"HH"];
[comps setHour:05];
[dateFormat setDateFormat:@"mm"];
[comps setMinute:30];

NSDate *reminderDate=[Calander dateFromComponents:comps];

    //NSLog(@"Current Date is :- '%@'",reminderDate);

    //NSLog(@"Current Date is :- '%@'",currentDate);

    NSTimeInterval ti = [reminderDate timeIntervalSinceDate:currentDate];

    //NSLog(@"Time Interval is :- '%f'",ti);
    int days = ti/86400;

[dateFormat release];
[Calander release];
[comps release];

希望它对你有用......

NSCalendar *Calander = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDateComponents *comps = [[NSDateComponents alloc] init];

[dateFormat setDateFormat:@"dd"];
[comps setDay:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:@"MM"];
[comps setMonth:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:@"yyyy"];
[comps setYear:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:@"HH"];
[comps setHour:05];
[dateFormat setDateFormat:@"mm"];
[comps setMinute:30];

NSDate *currentDate=[Calander dateFromComponents:comps];

NSLog(@"Current Date is :- '%@'",currentDate);


[dateFormat setDateFormat:@"dd"];
[comps setDay:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:@"MM"];
[comps setMonth:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:@"yyyy"];
[comps setYear:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:@"HH"];
[comps setHour:05];
[dateFormat setDateFormat:@"mm"];
[comps setMinute:30];

NSDate *reminderDate=[Calander dateFromComponents:comps];

    //NSLog(@"Current Date is :- '%@'",reminderDate);

    //NSLog(@"Current Date is :- '%@'",currentDate);

    NSTimeInterval ti = [reminderDate timeIntervalSinceDate:currentDate];

    //NSLog(@"Time Interval is :- '%f'",ti);
    int days = ti/86400;

[dateFormat release];
[Calander release];
[comps release];

Hope It will work for you........

一花一树开 2024-11-15 14:50:02

更简单的方法是:

// This just sets up the two dates you want to compare
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:@"01-01-2011"];
NSDate *endDate = [formatter dateFromString:@"25-03-2011"];

// This performs the difference calculation
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

// This just logs your output
NSLog(@"Start Date, %@", startDate);
NSLog(@"End Date, %@", endDate);
NSLog(@"%ld", [difference day]);

结果是:

开始日期,2011-01-01 00:00:00 +0000

结束日期,2011-03-25 00:00:00 +0000

83

尝试使用和操作秒来计算时间差是一个坏主意。 Cocoa 提供了大量用于日历计算的类和方法,您应该尽可能多地使用它们。

A simpler way of doing it is:

// This just sets up the two dates you want to compare
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:@"01-01-2011"];
NSDate *endDate = [formatter dateFromString:@"25-03-2011"];

// This performs the difference calculation
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

// This just logs your output
NSLog(@"Start Date, %@", startDate);
NSLog(@"End Date, %@", endDate);
NSLog(@"%ld", [difference day]);

And the results are:

Start Date, 2011-01-01 00:00:00 +0000

End Date, 2011-03-25 00:00:00 +0000

83

Trying to use and manipulate seconds for calculating time differences is a bad idea. There are a whole load of classes and methods provided by Cocoa for Calendrical calculations and you should use them as much as possible.

短叹 2024-11-15 14:50:02

试试这个

- (int) daysToDate:(NSDate*) endDate
{
    //dates needed to be reset to represent only yyyy-mm-dd to get correct number of days between two days.
    NSDateFormatter *temp = [[NSDateFormatter alloc] init];
    [temp setDateFormat:@"yyyy-MM-dd"];
    NSDate *stDt = [temp dateFromString:[temp stringFromDate:self]];
    NSDate *endDt =  [temp dateFromString:[temp stringFromDate:endDate]];
    [temp release]; 
    unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt  toDate:endDt  options:0];
    int days = [comps day];
    [gregorian release];
    return days;
}

Try this

- (int) daysToDate:(NSDate*) endDate
{
    //dates needed to be reset to represent only yyyy-mm-dd to get correct number of days between two days.
    NSDateFormatter *temp = [[NSDateFormatter alloc] init];
    [temp setDateFormat:@"yyyy-MM-dd"];
    NSDate *stDt = [temp dateFromString:[temp stringFromDate:self]];
    NSDate *endDt =  [temp dateFromString:[temp stringFromDate:endDate]];
    [temp release]; 
    unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt  toDate:endDt  options:0];
    int days = [comps day];
    [gregorian release];
    return days;
}
野却迷人 2024-11-15 14:50:02

//尝试一下

if((![txtFromDate.text isEqualToString:@""]) && (![txtToDate.text isEqualToString:@""]))
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM/dd/yyyy"];
        NSDate *startDate = [formatter dateFromString:txtFromDate.text];
        NSDate *endDate = [formatter dateFromString:txtToDate.text];
        unsigned flags = NSDayCalendarUnit;
        NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

        int dayDiff = [difference day];

        lblNoOfDays.text =[NSString stringWithFormat:@"%d",dayDiff];
    }

//try it

if((![txtFromDate.text isEqualToString:@""]) && (![txtToDate.text isEqualToString:@""]))
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM/dd/yyyy"];
        NSDate *startDate = [formatter dateFromString:txtFromDate.text];
        NSDate *endDate = [formatter dateFromString:txtToDate.text];
        unsigned flags = NSDayCalendarUnit;
        NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

        int dayDiff = [difference day];

        lblNoOfDays.text =[NSString stringWithFormat:@"%d",dayDiff];
    }
一场春暖 2024-11-15 14:50:02

查找开始日期到结束日期之间的日期数。

 NSCalendar *cale=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned unitFlags=NSMonthCalendarUnit| NSDayCalendarUnit;
    NSDateComponents *comp1=[cale components:unitFlags fromDate:startDate toDate:endDate options:0];

    NSInteger days=[comp1 day];
    NSLog(@"Days %ld",(long)days);

to find the number of dates between start date to end date.

 NSCalendar *cale=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned unitFlags=NSMonthCalendarUnit| NSDayCalendarUnit;
    NSDateComponents *comp1=[cale components:unitFlags fromDate:startDate toDate:endDate options:0];

    NSInteger days=[comp1 day];
    NSLog(@"Days %ld",(long)days);
入怼 2024-11-15 14:50:02
NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                           fromDate:dateA
                                             toDate:dateB
                                            options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                           fromDate:dateA
                                             toDate:dateB
                                            options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
柠北森屋 2024-11-15 14:50:02
//write this code in .h file
{
    NSDate *startDate,*EndDate;
    NSDateFormatter *Date_Formatter;
}
//write this code in .h file`enter code here`
- (void)viewDidLoad
{
    [super viewDidLoad];
    Date_Formatter =[[NSDateFormatter alloc]init];
    [Date_Formatter setDateFormat:@"dd-MM-yyyy"];

    UIToolbar *numbertoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numbertoolbar.barStyle = UIBarStyleBlackTranslucent;
    numbertoolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:@"Next"
    style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],nil];
    [numbertoolbar sizeToFit];

    Txt_Start_Date.inputAccessoryView = numbertoolbar;
    [Txt_Start_Date setInputView:Picker_Date];
    Txt_End_Date.inputAccessoryView = numbertoolbar;
    [Txt_End_Date setInputView:Picker_Date];
    [Picker_Date addTarget:self action:@selector(updateTextfield:) forControlEvents:UIControlEventValueChanged];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)doneWithNumberPad
{

    if ([Txt_Start_Date isFirstResponder])
    {
        [Txt_Start_Date resignFirstResponder];
        [Txt_End_Date becomeFirstResponder];
    }
    else if([Txt_End_Date isFirstResponder])
    {
        [Txt_End_Date resignFirstResponder];

        startDate =[Date_Formatter dateFromString:Txt_Start_Date.text];
        EndDate =[Date_Formatter dateFromString:Txt_End_Date.text];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:startDate toDate:EndDate options:0];
        Lab_Total_Days.text =[NSString stringWithFormat:@"%ld",components.day];
    }

}
//write this code in .h file
{
    NSDate *startDate,*EndDate;
    NSDateFormatter *Date_Formatter;
}
//write this code in .h file`enter code here`
- (void)viewDidLoad
{
    [super viewDidLoad];
    Date_Formatter =[[NSDateFormatter alloc]init];
    [Date_Formatter setDateFormat:@"dd-MM-yyyy"];

    UIToolbar *numbertoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numbertoolbar.barStyle = UIBarStyleBlackTranslucent;
    numbertoolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:@"Next"
    style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],nil];
    [numbertoolbar sizeToFit];

    Txt_Start_Date.inputAccessoryView = numbertoolbar;
    [Txt_Start_Date setInputView:Picker_Date];
    Txt_End_Date.inputAccessoryView = numbertoolbar;
    [Txt_End_Date setInputView:Picker_Date];
    [Picker_Date addTarget:self action:@selector(updateTextfield:) forControlEvents:UIControlEventValueChanged];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)doneWithNumberPad
{

    if ([Txt_Start_Date isFirstResponder])
    {
        [Txt_Start_Date resignFirstResponder];
        [Txt_End_Date becomeFirstResponder];
    }
    else if([Txt_End_Date isFirstResponder])
    {
        [Txt_End_Date resignFirstResponder];

        startDate =[Date_Formatter dateFromString:Txt_Start_Date.text];
        EndDate =[Date_Formatter dateFromString:Txt_End_Date.text];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:startDate toDate:EndDate options:0];
        Lab_Total_Days.text =[NSString stringWithFormat:@"%ld",components.day];
    }

}
早茶月光 2024-11-15 14:50:02

请尝试这个。希望它能帮助你...

NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:@"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:@"MM/dd/YYYY HH:mm "]  // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(@"%@f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];

Please try this. Hope it helps you...

NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:@"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:@"MM/dd/YYYY HH:mm "]  // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(@"%@f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文