How to convert a DD-MM-YYYY date format string into a YYYY-MM-DD date format string or into a NSDate object in Objective-C?

寵の児 提交于 2019-12-06 02:04:28
Nick Cartwright

You can use NSDateFormatter to format a date in Objective C.

Here's a quick example which might not do exactly what you want, but should hopefully give some pointers:

// Convert my dd-mm-yyyyy string into a date object
NSString *stringDate = @"01-02-2011";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];

NSDate *date = [dateFormatter dateFromString:stringDate];

// Convert my date object into yyyy-mm-dd string object
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *formattedStringDate = [dateFormatter stringFromDate:date];

[dateFormatter release];

Hope this helps!

Nick.

Using Nick's tutorial and answer the solution is :

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd.MM.yyyy"];

        NSDate *date = [dateFormatter dateFromString:@"01.02.1989"];

        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
        // Convert my date object into yyyy-mm-dd string object
        [dateFormatter1 setDateFormat:@"yyyy-MM-dd"];
        NSString *formattedStringDate = [dateFormatter1 stringFromDate:date];

        [dateFormatter release];
        [dateFormatter1 release];
        NSLog(formattedStringDate);

        objektObrat.dateOfObrat = [[NSString alloc] initWithString:formattedStringDate];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!