将NSSting转换为NSDate

时间:2015-08-10 18:15:40

标签: ios iphone nsstring nsdate

我有字符串2015-08-10T12:00如何将其转换为日期?

我的代码不起作用

      [self.dataFormatter setDateFormat:@"yyyy-MM-ddTHH:mm"];
            NSDate *date = [self.dataFormatter dateFromString:dateStg];

2 个答案:

答案 0 :(得分:1)

使用此日期格式:

yyyy-MM-dd'T'HH:mm

答案 1 :(得分:-1)

将当前日期转换为字符串

//Get Current Date
    NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    assert(en_US_POSIX != nil);
    NSDate *currentTime = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:en_US_POSIX];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *resultString = [dateFormatter stringFromDate: currentTime];

转换当前时间inTo NSString

 //Get Current Date
    NSDate* now = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour  | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
    NSInteger hour = [dateComponents hour];
    NSString *am_OR_pm=@"AM";
    if (hour>12){
        hour=hour%12;
        am_OR_pm = @"PM";
    }
    NSInteger minute = [dateComponents minute];
    NSString *strTime=[NSString stringWithFormat:@"%02d:%02d %@", hour, minute ,am_OR_pm];

将NSString转换为NSDate

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - 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];