从Objective C和iOS中的24小时格式时间字符串中获取不正确的日期

时间:2017-01-02 12:20:51

标签: ios objective-c nsdate nsdateformatter

我必须从24小时格式(HH:mm)时间字符串中获取格式(YYYY-MM-dd hh:mm:ss)的日期。

我使用了以下代码,但输出错误:

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]];
 [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
 [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
 [formatter setDateFormat:@"HH:mm"];

 NSDate *myDate = [formatter dateFromString:@"13:54"];

我输出错误:2000-01-01 13:54:00 +0000

但我希望输出像“2017-01-02 13:54:00”

我查了this question但没有得到正确的解答。

3 个答案:

答案 0 :(得分:2)

输出正确。

没有年/月/日信息的日期字符串会导致NSDateFormatter中的日期为2000/1/1。

您需要获取当前日期,并将hourminute组件替换为日期字符串。

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[formatter setDateFormat:@"HH:mm"];
NSDate *myDate = [formatter dateFromString:@"13:54"];
NSDateComponents *myDateComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:myDate];
todayComponents.minute = myDateComponents.minute;
todayComponents.hour = myDateComponents.hour;
NSDate *myCompleteDate = [calendar dateFromComponents:todayComponents];

答案 1 :(得分:1)

试试这段代码..

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
NSString *myString = [dateFormatter stringFromDate:myDate];

答案 2 :(得分:0)

试试这个

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:yourdateString];

NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; // <- Local time zone
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
            NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;



NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval    sinceDate:date];

NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
            [dateFormatters setDateFormat:@"MMM dd yyyy hh:mm"];

self.callDate = [dateFormatters stringFromDate: destinationDate];