ios - 从 UTC 字符串获取日期

标签 ios objective-c cocoa-touch nsdate nsdateformatter

当我尝试将该字符串转换为变为空的日期时,我得到了一个字符串格式的日期。如何直接从下面的函数获取日期。

-(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];
}

最佳答案

回溯到日期的转换是无关紧要的。删除线条。

并将区域设置始终设置为固定值 (en_US_POSIX)

-(NSString *)getLocalDateTimeFromUTC:(NSString *)strDate
    {
    // create dateFormatter with UTC time format
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; //@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"
    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;
}

关于ios - 从 UTC 字符串获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59151174/

相关文章:

ios - 更新配置分布配置文件

ios - 如果从外部调用,NSMutableArray 为空?

ios - Firebase 性能监控如何拦截 iOS 中的传出 http 请求?

ios - 如何在 iOS 8 上检测预测文本

javascript - 带逗号的 iOS 小键盘输入类型

ios - “显示缩放”iPhone 6/6s 设置模糊图形

ios - NSLinguisticTagger 在 Mac 和 iOS 上提供不同的输出

iphone - 在启动动画之前修改 iPhone 动画容器 View

objective-c - 将图像从 URL 加载到 UITableViewCell 的 UIImageView

IOS预期表达式错误