Converting NSString to NSDate (and back again)

后端 未结 17 2517
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:26

How would I convert an NSString like \"01/02/10\" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDat

17条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 00:17

    NSString *mystr=@"Your string date";
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *now = [dateFormatter dateFromString:mystr];
    
    Nslog(@"%@",now);
    

    If you want set the format use below code:

    NSString *dateString = @"01-02-2010";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    // this is important - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *dateFromString = [[NSDate alloc] init];
    
    // voila!
    dateFromString = [dateFormatter dateFromString:dateString];
    Nslog(@"%@",[dateFormatter dateFromString:dateString]);
    

提交回复
热议问题