Converting NSString to NSDate (and back again)

后端 未结 17 2481
-上瘾入骨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条回答
  •  情书的邮戳
    2020-11-21 23:55

    Best practice is to build yourself a general class where you put all your general use methods, methods useful in almost all projects and there add the code suggested by @Pavan as:

    + (NSDate *)getDateOutOfString:(NSString *)passedString andDateFormat:(NSString *)dateFormat{
    
        NSString *dateString = passedString;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:dateFormat];
        NSDate *dateFromString = [[NSDate alloc] init];
        dateFromString = [dateFormatter dateFromString:dateString];
        return dateFromString;
    
    }
    

    .. and so on for all other useful methods

    By doing so you start building a clean reusable code for you app. Cheers!

提交回复
热议问题