指定日期的月值出错?

时间:2015-08-14 09:52:34

标签: ios objective-c calendar nsdate nsdatecomponents

以下是我的代码:

data.table

现在:当endDate = 2015-08-31 23:59:59 +0000时,我的月份为9!这导致错误的endDayValue。这里出了什么问题?

修改

以下是我计算endDate的方法:

NSDateComponents *componenetsForEnd = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:endDate];
NSInteger endDay = [componenetsForEnd day];
NSInteger endMonth = [componenetsFoeEnd month];
NSInteger endDayValue = componenetsForEnd.weekday;

这个方法以[NSDate date]为今天的日期,这就是它:

NSDate *endDate = [self endOfMonthForDate:todayDate];

还尝试执行这些操作以在systemTimeZone中使用dateFormatter创建NSDateComponents和NSDate:

- (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd andDate: (NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents * months = [[NSDateComponents alloc] init];
[months setMonth: monthsToAdd];

return [calendar dateByAddingComponents: months toDate: date options: 0];
}

- (NSDate *) endOfMonthForDate: (NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];

NSDate * plusOneMonthDate = [self dateByAddingMonths: 1 andDate:date];


NSDateComponents * plusOneMonthDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: plusOneMonthDate];

NSDate * endOfMonth1 = [[calendar dateFromComponents: plusOneMonthDateComponents] dateByAddingTimeInterval: -1]; // One second before the start of next month
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:endOfMonth1];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:endOfMonth1];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* endOfMonth = [[NSDate alloc] initWithTimeInterval:interval sinceDate:endOfMonth1];

return endOfMonth;
}

2 个答案:

答案 0 :(得分:0)

而不是使用当前日历

var customer = {
    FirstName: "",
    LastName: "MyLastName",
    Email: "",
}; 

for(var propertyName in customer) {
   var propertyValue = customer[propertyName];
   console.log('LIST PROPERTIES: ', propertyName, propertyValue);
   
   if(propertyName == "LastName" && propertyValue == "MyLastName") {
       // do something
       console.log('your ' + propertyName + ' is ' + propertyValue);
   }
}

你可以使用:

[NSCalendar currentCalendar]

答案 1 :(得分:0)

问题在于我认为是这样的:在计算日,月或小时,分钟和秒时,您需要指定dateComponents的时区是UTC,即GMT。但是,我的endDateProper在系统时区。

所以,这样做对我有用:

NSDateComponents *componenetsForEnd = [greCalendar componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] fromDate:endDateProper];