开发者

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?

开发者 https://www.devze.com 2023-02-08 15:16 出处:网络
I have read date from XML which give开发者_C百科 me back string where the date is like DD-MM-YYYY. But when I want to add it to my core data database, SQLite sorts me that wrong so I have to convert i

I have read date from XML which give开发者_C百科 me back string where the date is like DD-MM-YYYY. But when I want to add it to my core data database, SQLite sorts me that wrong so I have to convert it to date format or to string like: YYYY-MM-DD. But SQLite does not support either Date() or To_Date() functions. Can you help me?


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];
0

精彩评论

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