Objective c 在iPhone中将多个日期格式转换为单一格式

Objective c 在iPhone中将多个日期格式转换为单一格式,objective-c,ios,nsdateformatter,Objective C,Ios,Nsdateformatter,我从html源代码生成PDF。我逐行读了所有的课文。我需要从整个文件中获取所有日期。我确实用正则表达式得到了所有的日期。问题是我需要将任何日期格式(dd-MM-yyyy或yyyy-MM-dd或dd/MM/yyyy)的字符串转换为特定的日期格式(dd-MMMM-yyyy)。我被这件事缠住了。任何帮助都会很好。我需要读取包含的日期格式字符串。这是我的密码 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,

我从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);


    }

}
NSArray*path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documentsDirectory=[paths objectAtIndex:0];
NSString*fileDocumentDirectorySavePath=[DocumentsDirectoryStringByAppendingPathComponent:@“Sample.txt”];
NSFileManager*fm=[NSFileManager defaultManager];
如果(![fm fileExistsAtPath:fileDocumentDirectorySavePath])
[fm copyItemAtPath:fileBundlePath-toPath:fileDocumentDirectorySavePath错误:nil];
NSString*文件内容=
[NSString stringWithContentsOfFile:fileDocumentDirectorySavePath
编码:NSUTF8StringEncoding错误:nil];
//首先,用新行分隔
NSArray*所有行字符串=
[fileContents组件按字符分隔集:
[NSCharacterSet newlineCharacterSet]];
NSString*strsInOneLine;
NSArray*日期数组;
//(1-1-9[1-9[1-9[1-9[1-9[1-9[12[0-9 9[0 0 0 0 0 0 3[1[0 0 0 1)3[1[1[0 0 0[1[1[1[1 1-1 5 5 5 5 5 5 5 5 5[1-1-5 5 5 5 5 5 5 5 5)及(1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1]及及及及日日日日日日日日日日)第三\\\\124;第三124;第三124;第三\124;日日日,,,,[19 |;(19 124;20)19 124;20)20))))))\\[19\\\\d{2})”;
(1-1-9[1-9[1-9[1-9[1-9[1-9[12[0-9 9[0 0 0 0 0 0 3[1[0 0 0 1)3[1[1[0 0 0[1[1[1[1 1-1 5 5 5 5 5 5 5 5 5[1-1-5 5 5 5 5 5 5 5 5)及(1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1]及及及及日日日日日日日日日日)第三\\\\124;第三124;第三124;第三\124;日日日,,,,[19 |;(19 124;20)19 124;20)20))))))\\[19\\二月(星期日)四月(星期日)六月(九月(星期日)十一月(余烬)月(余烬)月(余烬)月(余烬)月(余烬)|[13579][[26[13579][[26]除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除除{2})”;
n错误*错误=NULL;
NSRegularExpression*regex=[NSRegularExpression regular expression with pattern:regular expression
选项:nsregularexpressioncase不敏感
错误:&错误];
NSString*resultString;
对于(int i=0;i<[AlllinedString计数];i++){
strsInOneLine=[allLinedStrings objectAtIndex:i];
DateArray=[regex MatchesInstalling:StrsineLine选项:0范围:NSMakeRange(0[StrsineLine长度])];
for(日期数组中的NSTextCheckingResult*结果)
{
结果字符串=[strsineline substringWithRange:result.range];
NSLog(@“结果字符串====>%@”,结果字符串);
NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
[日期格式化程序setDateFormat:@“dd-MM-yyyy”];
NSDate*yourDate=[dateFormatter dateFromString:resultString];
NSLog(@“新日期====>%@”,yourDate);
NSString*myDateStr;
[日期格式化程序setDateFormat:@“dd-MMMM-yyyy”];
myDateStr=[dateFormatter stringFromDate:yourDate];
NSLog(@“新日期字符串====>%@”,myDateStr);
}
}

没有直接的方法可以做到这一点。但是,有一种类似的解决方法,在大多数情况下都能奏效。您所要做的就是将所有可能的日期格式化程序添加到下面的
日期格式化程序列表中

- (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

Javascript可以在这方面做得非常出色,现在您可以直接从Swift中调用它了!(我肯定目标C也是如此)

例如:

import JavaScriptCore

let context = JSContext()
let result: JSValue = context.evaluateScript("Date.parse('2016/5/6')")
let date: NSDate = result.toDate()
Boom!…以及从变量传递日期的示例:

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

它是否只包含这些(dd-MM-yyyy或yyy-MM-dd或dd/MM/yyyy)3种格式或任何其他格式?@Vishy:共有6种日期格式(dd-MM-yyyy、dd/MM/yyyyy、yyyy-MM-dd、yyyy/MM/dd,2012年7月2日、2012年1月31日)。我需要将所有这些转换为一种日期格式,即dd-mm-yy。我想你可以通过一系列if条件来实现这一点。@user1448493,检查我发布的代码。检查这是否有帮助。@ACB非常感谢你。。效果很好。但是你能告诉我2012年8月2日的日期格式是什么吗?非常感谢。效果很好。但是你能告诉我吗告诉我2012年8月2日的日期格式是什么???@user1448493,此代码也适用于此。@“d'nd'MMMM yyyy”已包含在列表中。如果要将其设置为上述代码中的targetDateFormatString,它将不适用于其他类型,如1号和3号等。您可能需要为此发布不同的问题。我已更新了我的代码,使其成为一个方法。将其放入类中,并将该方法调用为[self-dateStringFromString:@“2012年8月2日”destinationFormat:@“dd-MM-yyyy”];您将获得2012年8月2日的结果。请查看。只是提醒一下——在一些非常简单的格式上,它似乎让我失望,所以请谨慎使用