-2

我的申请中有一个日期,格式如下:

"MMM dd, yyyy hh:mm:ss a"

用户从选择器中选择一天,并且日期始终转换为此格式。从这种格式我怎样才能得到正好 24 小时后的日期?

例如,如果日期是Mon 24 , 2012 17:44:33我需要将其转换为Tue 25 , 2012 17:44:33.

4

3 回答 3

2
  1. 阅读日期和时间编程指南

  2. 使用日期格式化程序从字符串生成日期。

  3. 在日期上加一天。

  4. 使用日期格式化程序从新日期生成字符串。

于 2012-07-18T14:04:09.677 回答
1

使用以下代码NSDate从您的字符串创建一个:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setCalendar:[NSCalendar currentCalendar]];
[dateFormatter setDateFormat:<FORMAT_OF_DATE_STRING>];
NSDate *date = [dateFormatter dateFromString:<DATE_STRING>];
[dateFormatter release];

使用以下代码将天数添加到 a NSDate

    NSDate *today =<YOUR_DATE>        
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    /*
     Create a date components to represent the number of days to add to the current date.         
     The weekday value for Sunday in the Gregorian calendar is 1, so add 1 from the number of days to subtract from the date in question.  (If today is Sunday, add 0 days.)    
     */
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];

    if(day<7)
    {
       [componentsToAdd setDay: day];
    }

    NSDate *calculateDay = [gregorian dateByAddingComponents:componentsToAdd
                                                      toDate:today options:0];

快乐编码!

于 2012-07-18T14:13:45.673 回答
1

这是设置日期格式化程序所需的代码:

NSString *dateString = @"Tue 24 , 2012 17:44:33";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"EEE dd , yyyy HH:mm:ss"];

NSDate *theDate = [dateFormat dateFromString:dateString];

theDate = [NSDate dateWithTimeInterval:(60*60*24) sinceDate:theDate];

NSString *newDate = [dateFormat stringFromDate:theDate];

NSLog(@"%@",newDate);

控制台返回:

2012-07-18 09:26:28.395 TesterProject[71645:f803] Wed 25 , 2012 17:44:33

不过,您确实应该包括一个月,因为如果您不这样做,它只会占用当前月份,这可能会影响您一周中的某一天。

我使用了您输入的日期的实际格式,而不是您在问题中输入的错误格式。有关日期格式的信息,请参阅unicode 标准

有关NSDateFormatter此处的信息,请参阅 Apple 文档:NSDateFormatter

编辑:这是一个替代实现:

NSString *dateString = @"Tue 24 , 2012 17:44:33";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"EEE dd , yyyy HH:mm:ss"];

NSDate *theDate = [dateFormat dateFromString:dateString];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

[offsetComponents setDay:1];

theDate = [gregorian dateByAddingComponents:offsetComponents toDate:theDate options:0];

NSString *newDate = [dateFormat stringFromDate:theDate];

NSLog(@"%@",newDate);

它返回完全相同的东西。

于 2012-07-18T14:27:45.823 回答