【问题标题】:Converting mutliple date format into a single format in iPhone在 iPhone 中将多种日期格式转换为单一格式
【发布时间】:2012-10-29 05:03:29
【问题描述】:

我从 html 源代码生成 PDF。我逐行阅读所有文本。我需要从整个文档中获取所有日期。我确实使用正则表达式获取所有日期。问题是我需要将可以是任何日期格式(dd-MM-yyyy 或 yyyy-mm-dd 或 dd/mm/yyyy)的字符串转换为特定的日期格式(dd MMMM yyyy)。我被这个困住了。任何帮助都会很棒。我需要阅读包含的日期格式字符串。这是我的代码...

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileDocumentDirectorySavePath = [documentsDirectory stringByAppendingPathComponent:@"Sample.txt"];

NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:fileDocumentDirectorySavePath])
    [fm copyItemAtPath:fileBundlePath toPath:fileDocumentDirectorySavePath error:nil];

NSString* fileContents = 
[NSString stringWithContentsOfFile:fileDocumentDirectorySavePath 
                          encoding:NSUTF8StringEncoding error:nil];

// first, separate by new line
NSArray* allLinedStrings = 
[fileContents componentsSeparatedByCharactersInSet:
 [NSCharacterSet newlineCharacterSet]];
NSString* strsInOneLine;
NSArray *DateArray;
// NSString * regularExpression = @"([1-9]|0[1-9]|[12][0-9]|3[01])(st|nd|rd|th) \\w* (19|20)\\d\\d |(\\d{2}-\\d{2}-\\d{4})|(\\d{4}-\\d{2}-\\d{2})|(\\d{2}/\\d{2}/\\d{4})|(\\d{4}/\\d{2}/\\d{2})";

NSString * regularExpression = @"([1-9]|0[1-9]|[12][0-9]|3[01])(st|nd|rd|th) \\w* (19|20)\\d\\d |(\\d{2}-\\d{2}-\\d{4})|(\\d{4}-\\d{2}-\\d{2})|(\\d{2}/\\d{2}/\\d{4})|(\\d{4}/\\d{2}/\\d{2})|((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\Feb(ruary)?\\ (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]\\d)\\d{2})";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];
NSString *resultString;

for (int i = 0; i < [allLinedStrings count]; i++) {
           strsInOneLine = [allLinedStrings objectAtIndex:i];
    DateArray = [regex matchesInString:strsInOneLine options:0 range:NSMakeRange(0, [strsInOneLine length])];
    for (NSTextCheckingResult* result in DateArray)
    {
        resultString = [strsInOneLine substringWithRange:result.range];
        NSLog(@"RESULT STRING ===== >%@",resultString);

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
        NSDate *yourDate = [dateFormatter dateFromString:resultString];
        NSLog(@"NEW DATE ====== > %@",yourDate);
        NSString *myDateStr;
        [dateFormatter setDateFormat:@"dd MMMM yyyy"];
        myDateStr = [dateFormatter stringFromDate:yourDate];
        NSLog(@"NEW DATE STRING ====== > %@",myDateStr);


    }

}

【问题讨论】:

  • 它是否只包含这些(dd-MM-yyyy 或 yyyy-mm-dd 或 dd/mm/yyyy)3 种格式或其他任何内容?
  • @Vishy :共有 6 种日期格式(dd-mm-yyyy、dd/mm/yyyy、yyyy-mm-dd、yyyy/mm/dd、2012 年 7 月 2 日、2012 年 1 月 31 日) .我需要将所有这些都转换为一种日期格式,即 dd-mm-yy。
  • 我认为你可以使用一系列 if 条件来实现这一点..
  • @user1448493,检查我发布的代码。检查是否有帮助。
  • @ACB 非常感谢 .. 效果很好。但是你能告诉我 2012 年 8 月 2 日的日期格式是什么吗??

标签: objective-c ios nsdateformatter


【解决方案1】:

没有直接的方法可以得到这个。但是,在大多数情况下,有一个类似这样的解决方法。您所要做的就是将所有可能的日期格式化程序添加到下面的dateFormatterList

- (NSString *)dateStringFromString:(NSString *)sourceString destinationFormat:(NSString *)destinationFormat {

    NSString *convertedDateString = nil;
    NSArray *dateFormatterList = [NSArray arrayWithObjects:@"yyyy-MM-dd'T'HH:mm:ss'Z'", @"yyyy-MM-dd'T'HH:mm:ssZ",
                                  @"yyyy-MM-dd'T'HH:mm:ss", @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
                                  @"yyyy-MM-dd'T'HH:mm:ss.SSSZ", @"yyyy-MM-dd HH:mm:ss",
                                  @"MM/dd/yyyy HH:mm:ss", @"MM/dd/yyyy'T'HH:mm:ss.SSS'Z'",
                                  @"MM/dd/yyyy'T'HH:mm:ss.SSSZ", @"MM/dd/yyyy'T'HH:mm:ss.SSS",
                                  @"MM/dd/yyyy'T'HH:mm:ssZ", @"MM/dd/yyyy'T'HH:mm:ss",
                                  @"yyyy:MM:dd HH:mm:ss", @"yyyyMMdd", @"dd-MM-yyyy",
                                  @"dd/MM/yyyy", @"yyyy-MM-dd", @"yyyy/MM/dd",
                                  @"dd MMMM yyyy", @"MMddyyyy", @"MM/dd/yyyy",
                                  @"MM-dd-yyyy", @"d'st' MMMM yyyy",
                                  @"d'nd' MMMM yyyy", @"d'rd' MMMM yyyy",
                                  @"d'th' MMMM yyyy", @"d'st' MMM yyyy",
                                  @"d'nd' MMM yyyy", @"d'rd' MMM yyyy",
                                  @"d'th' MMM yyyy", @"d'st' MMMM",
                                  @"d'nd' MMMM", @"d'rd' MMMM",
                                  @"d'th' MMMM", @"d'st' MMM",
                                  @"d'nd' MMM", @"d'rd' MMM",
                                  @"d'th' MMM", @"MMMM, yyyy",
                                  @"MMMM yyyy", nil];

    //sourceString = @"20/11/2012";
    //destinationFormat  = @"dd MMMM yyyy";

    if (sourceString) {

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

        for (NSString *dateFormatterString in dateFormatterList) {

            [dateFormatter setDateFormat:dateFormatterString];
            NSDate *originalDate = [dateFormatter dateFromString:sourceString];

            if (originalDate) {

                [dateFormatter setDateFormat:destinationFormat];
                convertedDateString = [dateFormatter stringFromDate:originalDate];
                NSLog(@"Converted date String is %@", convertedDateString);
                break;
            }
        }
        [dateFormatter release];
    }

    return convertedDateString;
}

将此添加到您的班级并将其用作,

NSLog(@"%@", [self dateStringFromString:@"2nd August 2012" destinationFormat:@"dd-MM-yyyy"]);

输出:02-08-2012

【讨论】:

  • 非常感谢 .. 效果很好。但是你能告诉我 2012 年 8 月 2 日的日期格式是什么吗??
  • @user1448493,此代码也应该适用于此。 @"d'nd' MMMM yyyy" 包含在列表中。如果您想在上面的代码中将其设置为 targetDateFormatString,它将不适用于其他类型,例如 1st 和 3rd 等。您可能需要为此发布一个不同的问题。
  • 我已经更新了我的代码以使其成为一种方法。把它放在你的类中,并将方法称为 [self dateStringFromString:@"2nd August 2012"destinationFormat:@"dd-MM-yyyy"];您将获得 02-08-2012 的结果。看看吧。
【解决方案2】:

Javascript 可以做到这一点,现在您可以直接从 Swift 调用它! (我相信 Objective C 也是)

例子:

import JavaScriptCore

let context = JSContext()
let result: JSValue = context.evaluateScript("Date.parse('2016/5/6')")
let date: NSDate = result.toDate()

轰隆隆! ...以及从变量中传递日期的示例:

let randomFormatDate = "2016-05-06"
let jsDate = context.evaluateScript("Date.parse('\(randomFormatDate)')")
let cleanDate = jsDate.toDate()

【讨论】:

  • 请注意——在一些非常简单的格式上似乎让我失望了,所以请谨慎使用
猜你喜欢
  • 1970-01-01
  • 2017-08-27
相关资源
最近更新 更多