将NSString转换为NSDate的输出错误

时间:2016-05-24 05:21:13

标签: ios objective-c nsstring nsdate nsdateformatter

我尝试将NSString转换为NSDate对象,但NSDateFormatter会给我一个奇怪的值。我想要01/07/2016,但它会返回错误的输出。输出是:

  

今天:2015-12-20 00:00:00 +0000

这是代码:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

NSInteger day = 01;
NSInteger week = 07;
NSInteger year = [components year];

NSString *string = [NSString stringWithFormat:@"%ld/%ld/%ld",  (long)week,(long)day, (long)year];
NSLog(@"Min Date: %@",string);

NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateformate setDateFormat:@"MM/dd/YY"];

strMinDate = [dateformate dateFromString:string];
NSLog(@"Today: %@", strMinDate);

2 个答案:

答案 0 :(得分:1)

这里需要清理很多事情。

  1. 将您的week变量重命名为month
  2. 您的日期格式错误。它应该是@"MM/dd/yyyy
  3. 不要使用八进制数字。
  4. 这应该按照书面形式修复你的代码。

    但是,没有理由让NSDateFormatter参与其中。只需直接从更新的NSDateComponents创建新日期。

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    
    components.day = 1;
    components.month = 7; // July
    
    NSDate *minDate = [NSCalendar dateFromComponents:components];
    

    这将以当地时间为您提供新的日期。

    如果您拥有正确的NSDate,现在可以使用NSDateFormatter将其格式化为您选择的字符串。

    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"dd/MM/yy"];
    NSString *dayMonthYearStr = [dateFormat stringFromDate:minDate];
    

答案 1 :(得分:0)

您可以尝试以下代码:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

NSInteger day = 01;
NSInteger month = 07;
NSInteger year = [components year];

NSString *string = [NSString stringWithFormat:@"%ld/%ld/%ld",  (long)year,(long)month, (long)day];

NSLog(@"Min Date: %@",string);
NSString *date_str = string;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy/MM/dd"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithName:@"GMT"];
[dateFormat setTimeZone:gmt];
NSDate *date = [dateFormat dateFromString:date_str];
NSLog(@"%@",date);