简体   繁体   English

使用NSDateFormatter更改日期格式

[英]Change date format using NSDateFormatter

I want to use date format like this 2015-08-14 but unfortunately I am getting this format 16/11/15 我想使用类似2015-08-14日期格式,但不幸的是我正在使用这种格式16/11/15

Below is the code I have used to get desired output. 下面是我用来获取所需输出的代码。

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];

Can anyone please suggest how to fix this issue? 谁能建议如何解决这个问题?

在此处输入图片说明

Just remove the line [dateFormatter setDateStyle:NSDateFormatterShortStyle]; 只需删除[dateFormatter setDateStyle:NSDateFormatterShortStyle];

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

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

Try this out: 试试看:

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

Try this one. 试试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM