3

我正在尝试使用 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);
4

2 回答 2

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 文档

然后寻找基于 iOS 和 Mac OSX 版本的“固定格式”。你的目标。

于 2013-02-23T06:01:42.527 回答
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);
于 2013-02-22T23:44:18.977 回答