How to convert a DD-MM-YYYY date format string int

2019-05-14 09:43发布

I have read date from XML which give 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?

2条回答
看我几分像从前
2楼-- · 2019-05-14 10:05

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.

查看更多
放我归山
3楼-- · 2019-05-14 10:21

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];
查看更多
登录 后发表回答