【问题标题】:How to create a custom date on iPhone如何在 iPhone 上创建自定义日期
【发布时间】:2011-03-17 07:51:23
【问题描述】:

我正在尝试使用 NSDateComponent 设置今天日期的一些组件,如下所示:

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:1];
    [comps setHour:1];
    [comps setMinute:44];
    NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDate *date = [cal dateByAddingComponents:comps toDate:[NSDate date] options:0];
    [comps release];
    NSLog(@"%@", date);

但此示例会将时间添加到当前日期。现在我想做的是添加一天,但将小时和分钟设置为指定的值(不添加)。我该怎么做?

【问题讨论】:

    标签: iphone time nsdate nsdatecomponents


    【解决方案1】:

    这最终奏效了:

    NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSYearCalendarUnit
    NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
    [comp setDay:[comp day] +1];
    [comp setHour: 12];
    [comp setMinute: 00];
    NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comp];
    

    【讨论】:

    • 其实我在这里做的是加一天,把时间设置为12:00
    【解决方案2】:

    简单:只需使用date 属性...

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:1];
    [comps setHour:1];
    [comps setMinute:44];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *date = [gregorian dateFromComponents:comps];
    

    编辑:忘记日历。来自手册(NSDateComponents 的第一页,粗体):

    重要提示:一个 NSDateComponents 对象本身是没有意义的;您需要知道它是根据什么日历解释的,并且您需要知道这些值是单位的绝对值还是单位的数量。

    还有一个如何使用它的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多