当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Getting wrong date on changing date format

问题描述:

i'm getting wrong date on changing format of date , i'm using following code

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

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

NSDate * theDate = [NSDate dateWithTimeIntervalSince1970:1419929948.7490001];

NSString * dateStr = [formatter stringFromDate:theDate];

output -

theDate is : 2014-12-30 08:59:08 +0000

dateStr is : Dec 30, 2015

Thanks

网友答案:

You want to be using yyyy instead of YYYY. The small y is the calendar year, whereas the capital Y is the year of the "week of year".

Below is an explanation from 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.

网友答案:

Changes below line code.

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

Output is :

网友答案:

Use following line

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

网友答案:

by category class

+ (NSString *)dateStampFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy"];
    NSString *timeStamp = [dateFormatter stringFromDate:date];
    return timeStamp;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: