我尝试将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);
答案 0 :(得分:1)
这里需要清理很多事情。
week
变量重命名为month
。@"MM/dd/yyyy
。这应该按照书面形式修复你的代码。
但是,没有理由让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);