在更改日期格式时得到错误的日期

Getting wrong date on changing date format

我在更改日期格式时收到错误的日期,我正在使用以下代码

NSDateFormatter * formatter =  [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"MMM dd, YYYY"];

NSDate * theDate = [NSDate dateWithTimeIntervalSince1970:1419929948.7490001];

NSString * dateStr = [formatter stringFromDate:theDate];

输出 -

theDate is : 2014-12-30 08:59:08 +0000
dateStr is : Dec 30, 2015

谢谢

您想使用 yyyy 而不是 YYYY。小 y 是日历年,而大写 Y 是“一年中的一周”的年份。

以下是来自the specification的解释。

F.4 Week of Year

Values calculated for the Week of Year field range from 1 to 53 for the Gregorian calendar (they may have different ranges for other calendars). Week 1 for a year is the first week that contains at least the specified minimum number of days from that year. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (if needed). For example, January 1, 1998 was a Thursday. If the first day of the week is MONDAY and the minimum days in a week is 4 (these are the values reflecting ISO 8601 and many national standards), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. However, if the first day of the week is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998. The first three days of 1998 are then part of week 53 of 1997.

更改行代码下方。

[formatter setDateFormat:@"MMM dd, yyyy"];

输出为:

按类别 class

+ (NSString *)dateStampFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy"];
    NSString *timeStamp = [dateFormatter stringFromDate:date];
    return timeStamp;
}

使用下一行

[格式化程序 setDateFormat:@"MMM dd, yyyy"];