开发者

iPhone NSDateFormatter Convert String

I have the following string: NSString *dateStr = @"20开发者_开发技巧10-01-15"; which I'm trying to convert to January, 15th, 2010.

I'm currently using the following code, but it's returning (null).

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM d, YYYY"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];
incidentDate.text = [NSString stringWithFormat:@"%@", date];

Any advice? Thanks in advance!!


Modify your code as given below, will give you desired result.

    NSString *dateStr = @"2010-01-15";
    NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
    [dtF setDateFormat:@"YYYY-mm-dd"];
    NSDate *d = [dtF dateFromString:dateStr];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM d, YYYY"];
    NSString *st = [dateFormat stringFromDate:d];   
    [dtF release];
    [dateFormat release];
    incidentDate.text = [NSString stringWithFormat:@"%@", st];


Change

[dateFormat setDateFormat:@"MMMM d, YYYY"];

to

[dateFormat setDateFormat:@"yyyy-MM-dd"];

to get date object from string..

Now to convert, I dont think you can achieve 'th' suffix using DateFormatters, This SO link will help you..

See dateFormatter documentation


Check This its working for me....

NSString *date = @"2011-01-25";
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"YYYY-MM-dd"];
NSDate *date1 = [format dateFromString:date];
[format setDateFormat:@"MMMM d, YYYY"];
date = [format stringFromDate:date1];


Try this one

NSString* ds=@"2010-01-15";
NSDateFormatter* df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate* dt=[df dateFromString:ds];
[df setDateStyle:kCFDateFormatterLongStyle];
NSString* p=[df stringFromDate:dt];

i checked in my application and it works fine.


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-dd-MM"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat setDateFormat:@"MMMM d, YYYY"];
incidentDate.text = [NSString stringWithFormat:@"%@", [dateFormat stringFromDate:date]];
[dateFormat release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜