Question

I have these lines of code, which creates a starting date, based on the first Monday of the week starting 1 second after Midnight:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd '00:00:01' a"];  //  one second after midnight
NSString *startDateString = [formatter stringFromDate:firstDayOfTheWeek];  

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
NSDate *nsdStart = [formatter dateFromString:startDateString];  

startDateString is 2014-03-31 00:00:01 AM (which is correct)

nsdStart is 2014-04-01 00:00:00 PDT (which is wrong!)

Now, I have to do the same for the ending date, with this code:

[formatter setDateFormat:@"yyyy-MM-dd '23:59:59' a"];  //  one second before midnight
NSString *endDateString = [formatter stringFromDate:lastDayOfTheWeek];  //  create end date string

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
NSDate *nsdEnd = [formatter dateFromString:endDateString];  //  convert to NSDate

The results are now: endDateString: 2014-04-06 23:59:59 PM (which is correct)

nsdEnd: nil

Why is nsdStart and nsdEnd not the same as original string dates used to create the nsd dates?

Was it helpful?

Solution

The problem here is wrong format for date.

You should use 'HH' for 24 hour time format instead of hh, looks like date formatter confused with 23 hours where max is 12 for that format.

details here : Date Format Patterns

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top