在Objective-C中设置日期格式

时间:2015-08-07 10:40:35

标签: ios objective-c iphone

我需要设置这样的格式:7 Aug 2015 14:42:11

这是我的代码:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *string = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date Current :- %@",string);

4 个答案:

答案 0 :(得分:3)

如果您使用此代码,则会获得7 Aug 2015 14:42:11

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd MMM YYYY HH:mm:ss";
NSString *string = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date Current :- %@",string);

您的错误是日期格式不正确,

@"yyyy-MM-dd HH:mm:ss"应为:@"dd MMM YYYY HH:mm:ss"

答案 1 :(得分:1)

试试这个

NSString myString = @"2012-11-22 10:19:04";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";     
NSDate *yourDate = [dateFormatter dateFromString:myString];
dateFormatter.dateFormat = @"dd-MMM-yyyy";
NSLog(@"%@",[dateFormatter stringFromDate:yourDate]);

希望它有所帮助。

答案 2 :(得分:1)

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"d MMM, YYYY HH:mm:ss"];
NSString *string = [dateFormat stringFromDate:[NSDate date]];
NSLog(@"Date Current :- %@",string);

//Date Current :- 7 Aug, 2015 16:29:48

输出

enter image description here

答案 3 :(得分:0)

Add this method to your utility class and pass the date whatever you want to convert

+(NSString *)dateToString:(NSDate *)date
{
    NSDateFormatter *dateFormat =[[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"dd MM yyyy HH:mm:ss"];
    return [dateFormat stringFromDate:date];
}