使用NSDateFormatter更改日期格式

时间:2015-10-15 08:31:22

标签: ios objective-c iphone nsdateformatter

我想使用类似 2015-08-14 的日期格式,但遗憾的是我的格式为 16/11/15

以下是我用来获得所需输出的代码。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];

[dateFormatter setDateStyle:kCFDateFormatterShortStyle];

NSString *formattedDateString = [dateFormatter stringFromDate:selectedDate];

有人可以建议如何解决这个问题吗?

4 个答案:

答案 0 :(得分:2)

$group

只需删除第[dateFormatter setDateStyle:NSDateFormatterShortStyle];

即可

答案 1 :(得分:0)

-(NSString*)stringFromDateWithFormat:(NSString*)formatString{

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    dateFormatter.dateFormat = formatString;
    return [dateFormatter stringFromDate:self];
}

答案 2 :(得分:0)

试试这个:

NSDate *selectedDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *formattedDateString = [dateFormatter stringFromDate:selectedDate];

NSLog(@"formattedDateString = %@", formattedDateString); // Prints 2015-10-15

答案 3 :(得分:0)

试试这个。

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"date is %@",dateString);