iOS NSDateFormatter Timezone

2019-07-28 03:42发布

问题:

I have some code that takes a string, turns it into a date, reformats it then spits it out as another string:

[formatter setDateFormat:@"YYYY'-'MM'-'DD','HH:mm:ss','ZZZ"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
NSDate *date = [formatter dateFromString:combinedString];
[formatter setDateStyle:NSDateFormatterLongStyle];
NSString *finishedString = [formatter stringFromDate:date];

Basically, it works fine except for the timezones. All of the input strings are in timezone -0400, and I want the reformatted string to be in that timezone also, but the reformatted string keeps being converted forward 4 hours, even after I added the setTimeZone: line. Basically, I don't want to change the time at all, I just want to reformat it, and I can't understand what I am doing wrong?

回答1:

It depends on format specified on the source of your dates. Most of the times I deal with dates in Unix/POSIX format. Then I use the following two lines of code:

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

Anyway, I recommend you to check the following Q&A from Apple Developers site: http://developer.apple.com/library/ios/#qa/qa1480/_index.html



回答2:

In Swift:

    // Formatter configuration
    let formatter: NSDateFormatter = NSDateFormatter()
    let posix: NSLocale = NSLocale(localeIdentifier: "en_US_POSIX")
    formatter.locale = posix
    formatter.dateFormat = "d.M.y"
    formatter.timeZone = NSTimeZone(name: "UTC")!

    // String to date
    let dateString: String = "1.1.2013"
    let defaultDate: NSDate = formatter.dateFromString(dateString)!
    println("defaultDate: \(defaultDate)")

    self.dateOfBirthUIDatePicker.date = defaultDate