将日期从奇怪的字符串转换为日期格式的日期和年份

时间:2016-01-28 08:40:43

标签: ios objective-c iphone xcode nsdateformatter

您好我正在解析API的终点,从那里我得到一个字符串,其中包含类似日期字符串 2016-01-18T13:28:06.357 ,但我想将此转换为< strong> 01年1月1日,我已尝试多次使用以下提到的不同格式之一。我们需要建议如何完成这项任务。

    NSString * date = [dictionary objectForKey:@"date"];
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[dateformat setDateFormat:@"dd MMM yyyy"];
NSDate *myDate = [dateformat date];

4 个答案:

答案 0 :(得分:3)

  // Objective C   
        NSString * date = [dictionary objectForKey:@"date"];
        NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
        [dateformat setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
        [dateformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
        NSDate *myDate = [dateformat dateFromString:date];

        [dateformat setDateFormat:@"dd MMM yyyy"];

        NSString *strDate=[dateformat stringFromDate:myDate];

 // Swift 3.0
       var date = (dictionary["date"] as! String)
       var dateformat = DateFormatter()
       dateformat.timeZone = NSTimeZone(name: "EST")
       dateformat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
       var myDate = dateformat.date(fromString: date)!

       dateformat.dateFormat = "dd MMM yyyy"
       var strDate = dateformat.string(from: myDate)

答案 1 :(得分:1)

您应该使用以下格式:

NSString *dateStr = @"2016-01-18T13:28:06.357";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

NSDate *date = [formatter dateFromString:dateStr];
// date is 2016-01-18 08:28:06 +0000

然后将该日期转换为您需要的format

答案 2 :(得分:0)

您也可以使用:

NSString *dateString = @"2016-01-18T13:28:06.357";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *date = [dateFormatter dateFromString:dateString];

// Convert date object into desired format
[dateFormatter setDateFormat:@"dd MMMM yy"];
NSString *newDateString = [dateFormatter stringFromDate:date];

NSLog(@"newDateString=%@",newDateString);

答案 3 :(得分:0)

您应该使用此格式代码

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    

//Get Date    
[formatter setDateFormat:@"dd"];
NSString *strDate = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date is - %@",strDate);

//Get Month    
[formatter setDateFormat:@"MMM"];
NSString *strMonth = [formatter stringFromDate:[NSDate date]];
NSLog(@"Month is - %@",strMonth);

//Get Year    
[formatter setDateFormat:@"yyyy"];
NSString *strYear = [formatter stringFromDate:[NSDate date]];
NSLog(@"Year is - %@",strYear);

记录是:

Date is - 05
Month is - Feb
Year is - 2016

设置更多格式Click Me