以指定格式获取日期

时间:2013-02-10 09:29:04

标签: iphone objective-c nsdate nsdateformatter

我使用"2013-02-10 09:26:52 +0000"以格式[NSDate date]获取当前日期 我希望日期格式为"Feb 10"

有人可以建议更正dateFormat吗?

4 个答案:

答案 0 :(得分:0)

使用NSDateFormatter类:

NSDateFormatter * myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:@"ddMMyy" options:0 locale:[NSLocale currentLocale]];

NSString * formattedDate = [myFormatter stringFromDate:[NSDate date]];

您可以在此处选择setDateFormat的输出格式:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html

答案 1 :(得分:0)

NSString *string = @"2013-02-10 09:26:52 +0000"; // The date in a string

//Convert the string to date with the same format 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"]; // Set format
NSDate *date = [dateFormat dateFromString:string];

//Create the new date format using NSDateFormatter 
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:@"MMM dd"]; // Set format

//Convert the date using dateFormat1
NSDate *formatDate= [dateFormat1 dateFromString:date]; // date with MMM dd

答案 2 :(得分:0)

您可以像这样设置日期格式化程序

 [dateFormatter setDateFormat:@"MMM d, yyyy hh:mm:ss"];

希望它能运作

答案 3 :(得分:0)

这是我的工作:

            NSDateFormatter* dateFormatterBegin = [[NSDateFormatter alloc] init];
            [dateFormatterBegin setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
            NSString *dateStringBegin = @"2013-02-10 09:26:52 +0000";
            NSDate* datebegin = [dateFormatterBegin dateFromString:[dateStringBegin stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange(dateStringBegin.length-3, 1)]];
            [dateFormatterBegin setDateFormat:@"MMM-dd"];
            NSString *beginDate = [[NSString alloc] initWithFormat:@"%s%@","Start Date : ",[dateFormatterBegin stringFromDate:datebegin]];

            NSLog(@"Your date is : %@",beginDate); 

            [dateFormatterBegin release];
            [beginDate release];