NSDateFormatter stringFromDate不返回字符串

时间:2013-02-22 23:34:09

标签: objective-c cocoa

我正在尝试使用NSDateFormatter将保存的日期更改为高峰标准时间,但它似乎无法正常工作。

它正在输出 “currentDate:2013-02-22 23:20:20 +0000 date with date formatter:other 2000-01-01 07:00:00 +0000” 到控制台。

看起来字符串没有正确创建,但我似乎是以我看到它正常调用的方式调用它。

建议?

    NSTimeZone * mtnTimeZ= [NSTimeZone timeZoneWithAbbreviation:@"MST"];

    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setTimeZone:mtnTimeZ];

    NSString * timeZ = [dateFormatter stringFromDate:currentDate];

    NSDate * newDate = [dateFormatter dateFromString:timeZ];
    NSLog(@"currentDate: %@ string With dateFormatter: %@ date made from string %@", currentDate, timeZ, newDate);

2 个答案:

答案 0 :(得分:4)

您需要按照工作顺序设置指定日期和时间格式的样式:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];

[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
NSString * dateCurrentTZ = [dateFormatter stringFromDate:[NSDate date]];

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"MST"]];
NSString * dateMSTZ = [dateFormatter stringFromDate:[NSDate date]];

NSLog(@"Date In Current Time Zone: %@", dateCurrentTZ);
NSLog(@"Date In MST: %@", dateMSTZ);

如果您想指定自己的格式:

NSDateFormatter Documentation

然后根据iOS和&amp ;;寻找“固定格式” Mac OSX版本。你是目标。

答案 1 :(得分:1)

尝试输入以下行:

[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
像这样:

NSTimeZone * mtnTimeZ= [NSTimeZone timeZoneWithAbbreviation:@"MST"];

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[dateFormatter setTimeZone:mtnTimeZ];

NSString * timeZ = [dateFormatter stringFromDate:currentDate];

NSDate * newDate = [dateFormatter dateFromString:timeZ];
NSLog(@"currentDate: %@ string With dateFormatter: %@ date made from string %@", currentDate, timeZ, newDate);