[英]Change date format using 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];
誰能建議如何解決這個問題?
-(NSString*)stringFromDateWithFormat:(NSString*)formatString{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
dateFormatter.dateFormat = formatString;
return [dateFormatter stringFromDate:self];
}
試試看:
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
試試這個。
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.