ios日期时间是上午日期格式化程序问题

时间:2014-02-25 12:29:05

标签: iphone ipad nsdate nsdateformatter

我正在尝试将日期字符串get从数据库更改为日期(mm.dd.yy)和时间(am pm)。 这样我就可以从sqlite获取日期时间:

rs=[db executeQuery:@"select *,strftime('%m.%d.%Y %H:%M',update_date) AS DATETIME from sales_order where deleted=0 and status=1 and customer_id=?  order by order_id desc",custId];

我得到日期时间字符串:

        NSString *dateTimeString = [rs stringForColumn:@"DATETIME"];//from nslog 02.25.2014 14:41

然后我启动日期格式化程序并获取日期:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[self getCurrentLocale]];

    [dateFormatter setDateFormat:@"mm dd YY hh:mm a"];//it is nil,i am stuck here also tried with mm.dd.YY hh:mm a
    NSDate *date = [dateFormatter dateFromString:dateTimeString];

任何建议 感谢

2 个答案:

答案 0 :(得分:0)

为什么不使用NSDataDetector


您是否不确定(或不关心)字符串中包含的日期格式,使用NSDataDetector解析日期

NSString *dateString = @"Wed, 03 Jul 2013 02:16:02 -0700";
__block NSDate *detectedDate;

//Detect.
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
[detector enumerateMatchesInString:dateString
                           options:kNilOptions
                             range:NSMakeRange(0, [dateString length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{ detectedDate = result.date; }];

为此制作了 NSString扩展

// Simple as this.   
date = dateString.dateValue;

感谢NSDataDetector,它识别了很多格式。

'2014-01-16' dateValue is <2014-01-16 11:00:00 +0000>
'2014.01.16' dateValue is <2014-01-16 11:00:00 +0000>
'2014/01/16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16th' dateValue is <2014-01-16 11:00:00 +0000>
'20140116' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014' dateValue is <2014-01-16 11:00:00 +0000>
'01.16.2014' dateValue is <2014-01-16 11:00:00 +0000>
'01/16/2014' dateValue is <2014-01-16 11:00:00 +0000>
'16 January 2014' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014 17:05:05' dateValue is <2014-01-16 16:05:05 +0000>
'01-16-2014 T 17:05:05 UTC' dateValue is <2014-01-16 17:05:05 +0000>
'17:05, 1 January 2014 (UTC)' dateValue is <2014-01-01 16:05:00 +0000>

eppz!kit的一部分,从GitHub获取类别NSString+EPPZKit.h

答案 1 :(得分:0)

我尝试过以下代码: -

    NSString *dateStr = @"02.25.2014 14:41";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];

    [dateFormatter setDateFormat:@"MM.dd.yyyy HH:mm"];
    NSDate *date = [dateFormatter dateFromString:dateStr];
    NSLog(@"date = %@",date);

我得到了以下输出日志: -

date = 2014-02-25 09:11:00 +0000

让我知道,它会有所帮助。