Search code examples
iosnsdateiphone-4cgaffinetransform

NSDate how to get current day's fraction/second for the current time zone


I'm trying to get a day fraction for the current day to align a sun across a clock dial. I can calculate the day fraction like this:

float dayFraction = (int)seconds%(86400+1)/86400.0;

The equation above when converted to radians would continuously animate the sun around the clock

This code calculates where to position the sun

CGAffineTransform transformHours = [self calculateLabelRelateivePositionFromCurrentTimeWithOffsetClockwiseInDegrees:((int)[NSDate timeIntervalSinceReferenceDate])%(86400+1)/86400.0*360 ];

The problem is that I need to get the day fraction for the current time zone. The equation below always uses GMT time. Is there a way to easily get timestamp or the current time zone offset to apply to the timestamp It would be great to have this account for daylight savings time too!?

((int)[NSDate timeIntervalSinceReferenceDate])%(86400+1)/86400.0

Update: Thank you for the suggestion, I ended up using the following code:

int gmtOffset =  [[NSTimeZone localTimeZone] secondsFromGMT];
int daylightOffset =  [[NSTimeZone localTimeZone] daylightSavingTimeOffset];

int daySecond = [NSDate timeIntervalSinceReferenceDate]+gmtOffset+daylightOffset)%

(86400+1)


Solution

  • NSInteger secondsFromGMT = [[NSTimeZone localTimeZone] secondsFromGMT];