2

In my app, I try to change the normal start & end of the day. So, I will set the start of the day to be at 04:00:00 and the end of the day to be next day at 03:59:59 and consider different timezones
My code is as following

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]  
                                       initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *comps = [gregorian  
         components:NSYearCalendarUnit|NSMonthCalendarUnit|         
        NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|
        NSTimeZoneCalendarUnit fromDate:date];
[comps setTimeZone:[NSTimeZone localTimeZone]];

// Start of Day
comps.hour = 4;
//comps.hour = 4 + ([[NSTimeZone localTimeZone] secondsFromGMT] / 60 / 60);
comps.minute = 0;
comps.second = 0;   
NSDate *startOfDay = [gregorian dateFromComponents:comps];
NSLog(@"Start of day %@", startOfDay);
//Prints Out: Start of day 2014-04-16 02:00:00 +0000

// End of Day 
comps.day = comps.day +1;
comps.second = -1;
NSDate *endOfDay = [gregorian dateFromComponents:comps];
NSLog(@"End of day %@", endOfDay);
//Prints Out: End of day 2014-04-17 01:59:59 +0000

Please, I have 3 questions:
1. Why the NSGregorianCalendar ignores setting its property timezone and I must add the timezone to the number of hours ?
2. Also, Why the timezone is not printed?
3. Is the shown code for computing end of day, good?

user807146
  • 103
  • 8
  • 1
    It's not quite clear what exactly you want to achieve. Do you want to get NSDate instances which represent beginning and the end of the day? – Yuriy Panfyorov Apr 16 '14 at 04:03
  • I don't want to get the normal beginning (00:00:00) and end (23:59:59) of the day. But I want to make the beginning of the day to be at 04:00:00 and the end of the day to be at (03:59:59) next day. – user807146 Apr 16 '14 at 11:51
  • 1
    I'm guessing you're confused by the NSLog output. Actually, NSDate's -description always prints GMT time (which is marked by +0000 time zone offset). I think the time was calculated correctly, assuming your local time zone is GMT+2. However, If you want to format the NSDate value according to your local preferences, use NSDateFormatter. Or take a look at -descriptionWithLocale: of NSDate. – Yuriy Panfyorov Apr 16 '14 at 18:07
  • Thanks, You are right for NSLog method. But what about [gregorian dateFromComponents:comps], why this method ignores the timezone I set before, and calculates the date for GMT. – user807146 Apr 18 '14 at 02:31
  • 1
    Take a look at the accepted answer here, it may clear things up: http://stackoverflow.com/questions/7325837/nscalendar-datefromcomponents-gmt-timezone-instead-of-systemtimezone – Yuriy Panfyorov Apr 18 '14 at 15:52
  • Yup, I'm sorry, I got it. Thanks a lot – user807146 Apr 19 '14 at 03:42

0 Answers0