从UTC字符串获取日期

时间:2019-12-03 06:17:31

标签: ios objective-c cocoa-touch nsdate nsdateformatter

在这里,当我尝试将字符串转换为日期为null时,我正在获取字符串格式的日期。如何直接从下面的函数获取日期。

-(NSString *)getLocalDateTimeFromUTC:(NSString *)strDate
    {
    // create dateFormatter with UTC time format
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"]; //@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDate *date = [dateFormatter dateFromString:strDate]; // create date from string

    // change to a readable time format and change to local time zone
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *timestamp = [dateFormatter stringFromDate:date];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *date2 = [dateFormatter dateFromString:timestamp];
    NSLog(@"%@", date2); //Mon Dec  2 00:00:00 2019. wrong formate
    return [dateFormatter stringFromDate:date];
}

1 个答案:

答案 0 :(得分:0)

与转换日期无关。删除行。

并将语言环境始终设置为固定值(en_US_POSIX)

-(NSString *)getLocalDateTimeFromUTC:(NSString *)strDate
    {
    // create dateFormatter with UTC time format
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; //@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"
    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSDate *date = [dateFormatter dateFromString:strDate]; // create date from string

    // change to a readable time format and change to local time zone
    dateFormatter.dateFormat = @"dd-MM-yyyy";
    dateFormatter.timeZone = [NSTimeZone localTimeZone];
    NSString *timestamp = [dateFormatter stringFromDate:date];
    NSLog(@"%@", timestamp); 
    return timestamp;
}