格式化 RFC3339 日期

Format RFC3339 dates

我从 API

收到以下字符串格式的日期
2015-04-18 06:08:28.000000

我希望日期格式为d/M/yyyy

我尝试了以下方法

NSString *datevalue = (NSString*)value;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d/M/yyyy"];
NSDate *date =  [formatter dateFromString:datevalue];
NSString *currentDate = [formatter stringFromDate:date];

这个 returns NIL,可能是什么问题,或者我如何在 objective-c 中格式化这些日期?

谢谢。

您不能使用相同的格式化程序来读取和写入日期字符串,因为它们是不同的。您输入的日期格式不正确。

// input string date: 2015-04-18 06:08:28.000000
// [formatter setDateFormat:@"d/M/yyyy"]; // incorrect
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"]; 

下面是示例代码

//
//  main.m
//  so29732496
//
//  Created on 4/19/15.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"Hello, World!");

        NSString *dateStringFromAPI = @"2015-04-18 06:08:28.000000";
        NSString * const kAPIDateFormat = @"yyyy-MM-dd HH:mm:ss.SSSSSS";

        // convert API date string
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:kAPIDateFormat];
        NSDate *apiDate =  [formatter dateFromString:dateStringFromAPI];


        // now if I was output the api date to another format
        // I have to change the formatter
        [formatter setDateFormat:@"dd/M/yyyy"];
        NSString *currentDate = [formatter stringFromDate:apiDate];

        NSLog(@"Current Date: %@", currentDate);
    }
    return 0;
}

只想添加到 Black Frog 的回答中:正如他所说,您需要不同的格式化程序 reading/writing。

但是正确的格式应该是:

[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];

根据 Apple 文档,小数秒的格式应为 'S'。

看这里: NSDateFormat

这里还有一个例子来完成你的任务:

    NSString *datevalue = @"2015-04-18 06:08:28.000000";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
    NSDate *date =  [formatter dateFromString:datevalue];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    NSString *currentDate = [formatter stringFromDate:date];

    NSLog(@"%@",date);
    NSLog(@"%@",currentDate);

您应该为日期格式化程序使用 yyyy-MM-dd HH:mm:ss.SSSSSSS 格式字符串,将 API 日期转换为 NSDate 对象,正如其他人所讨论的那样。但是,您还需要考虑此格式化程序的 timeZonelocale 属性。

  • 通常 RFC 3339 日期在 GMT 中交换。用你的 API 确认这一点,但通常是 GMT/UTC/Zulu。如果是这样,您可能还想明确设置时区:

    formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    

    但请确认 API 期望的时区。

  • 一个更微妙的问题是处理使用非公历的用户

    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    

有关详细信息,请参阅 Apple Technical Q&A 1480

显然,这些 dateFormattimeZonelocale 属性仅用于将 API 日期字符串转换为 NSDate 对象。然后为最终用户输出日期时,您将使用单独的格式化程序,默认为标准 timeZonelocale 属性,并使用您想要的任何 dateFormat 字符串作为输出。 (坦率地说,我通常不建议对用户输出格式化程序使用 dateFormat 字符串,而只是对 dateStyletimeStyle 属性使用适当的值。)