Converting date of format yyyy-MM-dd'T'HH:mm:ss.SSS

后端 未结 3 1202
梦如初夏
梦如初夏 2021-01-03 09:54

I have few NSDate objects which contain values compliant to this format yyy-MM-dd\'T\'HH:mm:ss.SSS

When I try to convert to a different for

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 10:47

    EDIT: Rereading your question, I think you've got a conceptual misunderstanding aside from anything else:

    I have few NSDate objects which contains values compliant to the following format

    As far as I'm aware (I'm not an Objective-C programmer, admittedly) an NSDate object doesn't know anything about formatting. It just represents an instant in time. It isn't aware of whether it was parsed from text or created in some other way.

    It's like an int - an int variable isn't in decimal or hex, it's just a number. It's when you format and parse that you specify that. Likewise, you use NSDateFormatter to describe the format you want at the point of parsing and formatting.


    You've currently only got one NSDateFormatter - you're setting the format to "yyyy-MM-dd'T'HH:mm:ss.SSS" then resetting it before you've called dateFromString. The code snippet you've given formats modelObj.createdDate into ISO-8601 format, but then tries to parse it using the "MMM dd, yyyy HH:mm" format.

    I suggest you have two separate NSDateFormatter objects:

    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    NSString *createdDateStr = [format stringFromDate:modelObj.createdDate];
    
    NSDateFormatter *shortFormat = [[NSDateFormatter alloc] init];
    [shortFormat setDateFormat:@"MMM dd, yyyy HH:mm"];
    
    NSDate *parsedDate = [isoFormat dateFromString:createdDateStr];
    NSLog(@"========= REal Date %@",[shortFormat stringFromDate:parsedDate]);
    

    Note that I've changed your formattedDate variable to parsedDate, as that's what it really is - an NSDate which has been created by parsing text.

    As noted in comments, unless you actually need to format and parse like this, you shouldn't. I included all of your original code just to show how you can format a date and then reparse it with the same NSDateFormatter. You'll get the same result with just:

    NSDateFormatter *shortFormat = [[NSDateFormatter alloc] init];
    [shortFormat setDateFormat:@"MMM dd, yyyy HH:mm"];    
    NSLog(@"========= REal Date %@",[shortFormat stringFromDate:modelObj.createdDate]);
    

    In general, you should avoid unnecessary conversions. Convert from text to the more natural data type (NSDate in this case, but the same applies for numbers etc) and use that data type for as much of your code as possible, only converting to text at the last moment.

提交回复
热议问题