簡體   English   中英

使用NSDateFormatter更改日期格式

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

誰能建議如何解決這個問題?

在此處輸入圖片說明

只需刪除[dateFormatter setDateStyle:NSDateFormatterShortStyle];

-(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM