【问题标题】:Setting NSDate from NSString从 NSString 设置 NSDate
【发布时间】:2011-12-02 02:52:27
【问题描述】:

我正在使用 XCode 4.2 开发 iPhone 应用程序,我是应用程序开发的新手

我有以下 NSStrings

NSString *year;
NSString *month;
NSString *day;
NSString *hour;
NSString *minute;

如何使用这些设置NSDate *date 变量

谢谢

【问题讨论】:

    标签: objective-c nsdate


    【解决方案1】:

    例子:

    NSString *year   = @"2011";
    NSString *month  = @"1";
    NSString *day    = @"2";
    NSString *hour   = @"3";
    NSString *minute = @"3";
    
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.year   = [year intValue];
    dateComponents.month  = [month intValue];
    dateComponents.day    = [day intValue];
    dateComponents.hour   = [hour intValue];
    dateComponents.minute = [minute intValue];
    
    NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
    NSLog(@"date: %@", date);
    

    NSLog 输出:

    date: 2011-01-02 08:03:00 +0000
    

    【讨论】:

      【解决方案2】:

      您基本上必须创建一个字符串,其中包含创建日期所需的所有字段。

      也就是说,类似于:

      NSString * dateString = [NSString dateWithFormat: @"%@-%@-%@ %@:%@", year, month, day, hour, minute];
      

      然后您可以关注 the solutions provided in this related questionthis other related question 来提出您的 NSDate(如果这些解决方案解释不够充分,您可以轻松进行搜索——“如何将 NSStrings 转换为 NSDate”的问题"在这里经常出现)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-01
        • 2018-03-10
        相关资源
        最近更新 更多