奇怪的将输出从 NSString 转换为 NSDate

Weird converting output from NSString to NSDate

我尝试从 NSString 输出 NSDate 对象时出现奇怪的结果。 我的 NSString 是:1976-06-11 我的转换方法是:

-(NSDate*)dateFromString:(NSString *)dateString{

    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateString];
    return date;
}

但它输出1976-06-10 21:00:00 +0000

怎么会这样? 1天之差。

您有 UTC 格式的日期。使用此代码将您的日期转换为当地时间:

NSTimeInterval seconds; // assume this exists
NSDate *ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];

NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init];
utcFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
utcFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz";

NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
localFormatter.timeZone = [NSTimeZone timeZoneWithName:@"EST"];
localFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz";

NSString *utcDateString = [utcFormatter stringFromDate:ts_utc];
NSString *LocalDateString = [localFormatter stringFromDate:ts_utc];

或者您可以使用 [NSTimeZone defaultTimeZone] 来防止时区名称的硬编码字符串。此方法returns系统时区,如果没有设置默认时区

func dateFromString(dateString: String) -> NSDate {
    // Convert string to date object
    var dateFormat = NSDateFormatter()
    dateFormat.dateFormat = "yyyy-MM-dd"
    dateFormat.timeZone = NSTimeZone(name: "UTC")
    var date = dateFormat.dateFromString(dateString)!
    print(date)
    return date
}

输出: 1976-06-11 00:00:00 +0000

您可以使用以下方法将 UTC 日期字符串转换为 UTC 日期和本地日期

 - (NSDate *)convertIntoGMTZoneDate:(NSString *)dateString
    {
        NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc]init];
        [gmtFormatter setDateStyle:NSDateFormatterFullStyle];
        [gmtFormatter setTimeStyle:NSDateFormatterFullStyle];
        [gmtFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

        return [gmtFormatter dateFromString:dateString];
    }

    - (NSDate *)convertIntoSystemZoneDate:(NSString *)dateString
    {
        NSDateFormatter *systemZoneFormatter = [[NSDateFormatter alloc]init];
        [systemZoneFormatter setDateStyle:NSDateFormatterFullStyle];
        [systemZoneFormatter setTimeStyle:NSDateFormatterFullStyle];
        [systemZoneFormatter setTimeZone:[NSTimeZone systemTimeZone]];

        return [systemZoneFormatter dateFromString:dateString];
    }

如果您调试代码,它会显示 1 天的差异,但在 运行 之后您会发现您输入的实际日期。

它适用于 me.I 我认为它会对您有所帮助。 谢谢