【问题标题】:Need to convert custom timestamp to different format in Objective-C iOS需要在 Objective-C iOS 中将自定义时间戳转换为不同的格式
【发布时间】:2012-05-30 19:41:30
【问题描述】:

我有一个字符串“2012-06-04”,我很难将其转换为:June 4, 2012

有没有一种快速的方法来改变它?我来自一个红宝石世界,你可以将所有内容转换为秒数,然后再转换为你需要的格式。有没有说明如何做到这一点的参考资料?

谢谢

【问题讨论】:

    标签: objective-c ios datetime date nsdateformatter


    【解决方案1】:

    这样做的一种方法是将字符串转换为使用 NSDateFormatter 格式为 2012-06-04 的 NSDate,然后将 NSDate 转换回使用 2012 年 6 月 4 日格式的字符串:

    NSString* input = @"2012-06-04";
    
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate* date = [df dateFromString:input];
    [df setDateFormat:@"MMMM d, yyyy"];
    
    return [df stringFromDate:date];
    

    格式字符串的语法在UTS #35中描述。

    【讨论】:

      【解决方案2】:

      类似

      NSDateFormatter *fromDateFormatter = [[NSDateFormatter alloc] init];
      fromDateFormatter.dateFormat = @"yyyy-MM-dd";
      
      NSDate *date = [fromDateFormatter dateFromString:@"2012-06-04"];
      
      NSLog(@"%@", date);
      
      NSDateFormatter *toDateFormatter = [[NSDateFormatter alloc] init];
      toDateFormatter.dateFormat = @"MMMM d, yyyy";
      
      NSString *toDate = [toDateFormatter stringFromDate:date];
      
      NSLog(@"%@", toDate);
      
      #=> 2012-05-30 20:51:12.205 Untitled[1029:707] 2012-06-03 23:00:00 +0000
      #=> 2012-05-30 20:51:12.206 Untitled[1029:707] June 4, 2012
      

      要解决这个问题,您可以使用 Apple 的类引用 NSDateFormatter 和其他来源,如 IPHONE NSDATEFORMATTER DATE FORMATTING TABLE 和一些试验和错误

      【讨论】:

        猜你喜欢
        • 2016-03-08
        • 2023-03-27
        • 1970-01-01
        • 2017-09-25
        • 2021-06-01
        • 2015-02-16
        • 2012-12-03
        • 2020-04-12
        • 1970-01-01
        相关资源
        最近更新 更多