【问题标题】:How to change the date type to "Jan 21, 2013 5:30 AM" using NSDateFormatter in iOS如何在 iOS 中使用 NSDateFormatter 将日期类型更改为“2013 年 1 月 21 日上午 5:30”
【发布时间】:2013-04-02 06:58:51
【问题描述】:

我希望将日期格式从“2013-01-21 11:55:00”更改为“Jan 21, 2013 5:30 AM”。

我尝试了以下代码。但它给出了一个固定的日期。

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

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];

NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSLog(@"%@",[dateFormatter stringFromDate:myDate]);

上面的代码给出了恒定的输出:2001 年 1 月 3 日 2:30:00 AM

但就我而言,日期是动态的。

【问题讨论】:

标签: iphone ios nsdateformatter


【解决方案1】:
    NSString *firstDate = @"2013-01-21 11:55:00";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd  HH':'mm':'ss"];
    NSDate *date = [dateFormatter dateFromString:firstDate];
    [dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"];

    NSLog(@"Expected Result___ %@",[dateFormatter stringFromDate:date]);

【讨论】:

    【解决方案2】:

    试试这个

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"];
    
    NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
    NSLog(@"%@",[dateFormatter stringFromDate:myDate];
    

    尝试使用[NSDate date] 而不是[NSDate dateWithTimeIntervalSinceReferenceDate:162000]

    【讨论】:

    • 我得到一个常量“2001 年 1 月 3 日凌晨 2:30”。但我需要动态转换。
    • 是的。当我使用 [NSDate date] 时,我现在已经获得了所需格式的今天日期。无论如何我可以动态传递日期吗?
    • 您可以从字符串中获取您的日期。stackoverflow.com/questions/5604657/converting-nsstring-to-date
    【解决方案3】:

    因为你给定的输入是 162000,所以你得到了恒定的输出!!!

    首先使用格式从字符串中获取日期,然后使用新格式从获取的日期中获取字符串

    使用它来输出格式为

    @"MMM d, yyyy h:mm a"
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"];
    NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多