获得本季度的第一个日期

时间:2014-05-15 15:44:59

标签: ios nsdate nscalendar

我正在尝试获取当前季度的第一个和最后一个日期,我正在使用它:

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

components.quarter = 1;

funStartDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"First day of quater: %@", funStartDate);

[components setQuarter:[components quarter]+1];

funEndDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"Last day of quater: %@", [funEndDate descriptionWithLocale:[NSLocale currentLocale]]);

但在两个控制台打印中,我看到了今天的日期。我做错了什么?

2 个答案:

答案 0 :(得分:8)

更新:我发现苹果公司的季度单位错误仍然存​​在于iOS 7.1中,因此请避免在日期组件中使用此单元。

我在这里为您找到了解决方案:

一季度的第一天:

    NSDate *date = <whatever>;
    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDate *startOfQuarter;
    [currentCalendar rangeOfUnit: NSQuarterCalendarUnit
                       startDate: &startOfQuarter
                        interval: NULL
                         forDate: date];
    NSLog(@"quarter starts at %@", startOfQuarter);

一季度的最后一天:

    NSDateComponents* comps = [currentCalendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                 fromDate:date];
    NSUInteger quartalNum = (comps.month - 1) / 3 + 1;
    NSUInteger lastQuartalMonthNum = quartalNum * 3;
    NSUInteger nextQuartalFirstMonth = lastQuartalMonthNum + 1
    [comps setMonth: nextQuartalFirstMonth];
    [comps setDay: 0]; // with 0 day we get last day of previous month

    NSLog(@"quarter ends at %@",  [currentCalendar dateFromComponents: comps]);

答案 1 :(得分:3)

Swift 3.1。四分之一部分仍无效。解决方法:

Date().startOfQuarter

用法:

#include <stdio.h>
#include <stdlib.h>

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;   
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}