Converting NSString to NSDate (and back again)

后端 未结 17 2505
-上瘾入骨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-22 00:15

    Why not add a category to NSString?

    // NSString+Date.h
    @interface NSString (Date)
    + (NSDate*)stringDateFromString:(NSString*)string;
    + (NSString*)stringDateFromDate:(NSDate*)date;
    @end
    
    
    // NSString+Date.m
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
    
    NSDate *date = [dateFormatter dateFromString:stringDate ];
    [dateFormatter release];
    + (NSDateFormatter*)stringDateFormatter
    {
        static NSDateFormatter* formatter = nil;
        if (formatter == nil)
        {
            formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
        }   
        return formatter;
    }
    
    + (NSDate*)stringDateFromString:(NSString*)string
    {
        return [[NSString stringDateFormatter] dateFromString:string];
    }
    
    + (NSString*)stringDateFromDate:(NSDate*)date
    {
        return [[NSString stringDateFormatter] stringFromDate:date];
    }
    
    
    // Usage (#import "NSString+Date.h") or add in "YOUR PROJECT".pch file
    NSString* string = [NSString stringDateFromDate:[NSDate date]];
    NSDate* date = [NSString stringDateFromString:string];
    

提交回复
热议问题