NSDate detection with NSDataDetector

前端 未结 2 1281
臣服心动
臣服心动 2021-02-04 13:32

I tried to get a NSDate from a NSString with UNKNOWN format, So I wrote a function like below

-(void)dateFromString:(NSString*)string {

    NSE         


        
相关标签:
2条回答
  • 2021-02-04 14:20

    You have to use NSDateFormatter. Try replace your if statement with:

    if ([match resultType] == NSTextCheckingTypeDate) {
       NSDate *dateAfter = [match date];
       NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
       [dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
       NSString *formattedDateString = [dateFormatter stringFromDate:dateAfter];
       NSLog(@"After: %@", formattedDateString);
    }
    

    If you want to display it in different format you have to change this line to required format:

    [dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
    

    If you want it to match your first example change it to:

    [dateFormatter setDateFormat:@"EEEE, MMMM dd, yyyy 'at' HH:mm:ss a zzzz"];
    
    0 讨论(0)
  • 2021-02-04 14:30

    Actually, the method I wrote works really well :). Unfortunately, the Region Format in my test phone was set to US and was never set back to Australia : My bad..

    @joiningss : Throw some random formatted date string to that methods and you will be amazed, how apple has made it easy for developers. Anyway, thank you so much.

    @mrt,Chavda&Greg : Thanks a lot guys. I really appreciate your help.

    0 讨论(0)
提交回复
热议问题