Reputation: 6335
I have this piece of code
NSDateComponents *comps = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:sender.date];
[comps setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSDate *converted = [[NSCalendar currentCalendar] dateFromComponents:comps];
Sender.date can be output to console like
1963-02-23 12:00:00 am +0000
But comps.day for UTC is giving me 22. Which I would expected to be 23 since that sender value in UTC is obviously containing day component equal to 23.
Is that somehow related to 12am? What am I missing here?
Thanks!
Upvotes: 1
Views: 52
Reputation: 437432
It depends upon your intent. Consider:
NSString *string = @"1963-02-23 12:00:00 am +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd hh:mm:ss a X";
NSDate *date = [formatter dateFromString:string];
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
NSLog(@"%@", comps);
This will report:
<NSDateComponents: 0x610000140420>
Calendar Year: 1963
Month: 2
Leap month: no
Day: 23
I can then convert that to a date in our local timezone with:
NSDate *converted = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSLog(@"%@", converted);
That will show that as midnight in my local timezone (GMT-8), which is 8am in GMT:
1963-02-23 08:00:00 +0000
But when I use a formatter to show this to the user, though, it shows that to me in my local timezone:
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
outputFormatter.dateStyle = NSDateFormatterMediumStyle;
outputFormatter.timeStyle = NSDateFormatterMediumStyle;
NSLog(@"%@", [outputFormatter stringFromDate:converted]);
That will show:
Feb 23, 1963, 12:00:00 AM
Obviously, use timeStyle
of NSDateFormatterNoStyle
if you don't want to show the time, but I included it just to show you what was really going on.
Personally, I find all of the above quite convoluted. I'm guessing that the original string was trying to reflect a date independent of any particular time and/or timezone (e.g. a birthday, an anniversary, etc.), then I think that everything is much easier if you omit the time and timezone information from the original string and just capture the date in yyyy-MM-dd
format and leave it at that. Then that simplifies much of the above code.
I might suggest clarifying your actual intent, why you're doing what you're doing, and we might be able to offer better counsel.
Upvotes: 1