【问题标题】:Converting an NSString result from SQLite into a formatted NSDate将 SQLite 中的 NSString 结果转换为格式化的 NSDate
【发布时间】:2019-06-11 01:22:34
【问题描述】:

我知道这听起来很熟悉,但由于某些奇怪的原因,大多数关于 SO 的建议解决方案都对我不起作用。

我有一个 从 SQLite 查询返回的日期字符串作为 NSString,格式如下:

2019-06-10 13:45:33

但是,当应用任何建议的日期格式化程序解决方案时,无论有没有时区本地化,我都会不断得到这样的结果:

Mon Jun 10 13:45:33 2019

这是我尝试过的例程之一,除此之外还有很多:

NSString * dateString = @"2019-06-10 13:45:33";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];

// dateFromString > Mon Jun 10 13:45:33 2019

是我做错了什么还是转换过程中缺少了一些步骤?

TIA。

【问题讨论】:

    标签: objective-c nsstring nsdate


    【解决方案1】:

    我猜你想要另一种输出格式,如果是这种情况,那么你可以试试这样的代码:

    NSString * dateString = @"2019-06-10 13:45:33";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    //[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:dateString];
    
    NSDateFormatter *printDateFormatter = [[NSDateFormatter alloc] init];
    printDateFormatter.dateStyle = NSDateIntervalFormatterMediumStyle;
    printDateFormatter.timeStyle = NSDateIntervalFormatterMediumStyle;
    
    NSLog(@"%@", [printDateFormatter stringFromDate:dateFromString]);
    

    结果将是:

    10 Jun 2019 at 13:45:33
    

    【讨论】:

      【解决方案2】:

      使用不同的格式化程序从日期格式化字符串。例如:

      NSDateFormatter * formatter=[[NSDateFormatter]alloc]init];
      formatter.dateStyle = NSDateFormatterMediumStyle;
      formatter.timeStyle = NSDateFormatterNoStyle;
      NSString * formattedDateString = [formatter stringFromDate:date];
      

      setDateFormat 用于输入日期字符串并获取 NSDates。

      dateStyle 和 timeStyle 用于格式化来自 NSDates 的 dateStrings。

      【讨论】:

        猜你喜欢
        • 2013-12-08
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多