Converting NSString to NSDate (and back again)

后端 未结 17 2515
-上瘾入骨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:54

    NSString to NSDate or NSDate to NSString

    //This method is used to get NSDate from string 
    //Pass the date formate ex-"dd-MM-yyyy hh:mm a"
    + (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate  {
    
        // Converted date from date string
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
        [dateFormatter setDateFormat:formate];
        NSDate *convertedDate         = [dateFormatter dateFromString:dateString];
        return convertedDate;
    }
    
    //This method is used to get the NSString for NSDate
    //Pass the date formate ex-"dd-MM-yyyy hh:mm a"
    + (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate {
    
        // Converted date from date string
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
        [dateFormatter setDateFormat:formate];
        NSString *convertedDate         = [dateFormatter stringFromDate:date];
        return convertedDate;
    }
    

提交回复
热议问题