NSDate Showing Wrong Day - ios

I am taking an NSDate, and pulling just a 2-digit number, representing the day of the month into an NSString. One of the dates in question is:
2013-11-30 00:00:00 +0000
I use:
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"dd"];
NSString *datefromdate = [formatter2 stringFromDate:articleDate];
NSLog(#"Date%#", datefromdate);
[formatter2 release];
but the log comes back
29

You are probably in a negative time zone i.e. GMT minus something. This is why 2013-11-30 00:00:00 +0000 GMT is on the 29th day when you log it. Set the formatter to GMT and you will be fine.

Set the timezone you want the time date formatter to use. NSDate is the first instant of 1 January 2001, GMT and thus has no timezone information in it.
So, this, according to Apple, is going to get complicated needing up to five classes: NSDateFormatter, NSDate, NSCalendar, NSTimeZone and finally NSDateComponents.
If all you want is the day you can use NSDateComponents.
Example:
NSString *dateString = #"2013-11-30 00:00:00 +0000";
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
[inDateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [inDateFormatter dateFromString:dateString];
NSLog(#"dateFromString: %#", date);
NSTimeZone *timezone = [NSTimeZone timeZoneForSecondsFromGMT:0];
// Using date formatter, result is a string
NSDateFormatter *outDateFormatter = [NSDateFormatter new];
[outDateFormatter setTimeZone:timezone];
[outDateFormatter setDateFormat:#"dd"];
NSString *dayString = [outDateFormatter stringFromDate:date];
NSLog(#"date formatter day: %#", dayString);
// Using date components, result is an integer
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone: timezone];
NSDateComponents *dateComponents = [calendar components:NSDayCalendarUnit fromDate:date];
NSInteger day = [dateComponents day];
NSLog(#"date components day: %i", day);
NSLog output:
dateFromString: 2013-11-30 00:00:00 +0000
date formatter day: 30
date components day: 30

Related

Adding an amount of hours to NSDate isn't working?

I've spent a good few hours trying to make this work. Here's what I'm trying to do:
Take input from a UITextField in the form HH:mm AM/PM
Convert that string into an NSDate object, and update the month/day/year properties of that NSDate to reflect the curren month/day/year.
Add 4 hours to the time of the NSDate object.
That last bit isn't working. It works for times such as 12:00 PM and 12:30 PM but for times such as 2:30 PM, it will output 4:30 PM rather than 6:30 PM as expected. Here is my code, broken up to reflect those three tasks.
Task 1 - checking to see if the text input was HH:mm AM/PM
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[format setTimeZone:[NSTimeZone systemTimeZone]];
[format setDateFormat:#"HH:mm a"];
NSString *dateString = textField.text;
NSLog(#"input datestring: %#", dateString);
NSDate *parsed = [format dateFromString:dateString];
if (parsed) {
NSLog(#"datestring is valid, %#", parsed);
}
Task 2- Updating the m/d/y components of that date to reflect today's.
//gregorian calendar, get the hour and minute components from the input time
NSCalendar *greg = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [greg components: NSCalendarUnitHour | NSCalendarUnitMinute fromDate:parsed];
//get the month/day/year components from the current date
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
//set the components of the original date to the month/day/year components of today
[components setYear:comps.year];
[components setDay:comps.day];
[components setMonth:comps.month];
//create the new date.
NSDate* newDate = [greg dateFromComponents:components];
NSLog(#"########### %#", newDate);
Task 3 - Add 4 hours.
int hours = 4 ;
NSString *output;
NSDateComponents *add = [[NSDateComponents alloc] init];
[add setHour:hours];
newDate = [greg dateByAddingComponents:add toDate:newDate options:0];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterShortStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
output = [df stringFromDate:newDate];
NSLog(#"new date: %#", output);
Log:
2015-08-27 16:03:35.672 Del Taco[1960:117431] input datestring: 2:30 pm
2015-08-27 16:03:35.673 Del Taco[1960:117431] datestring is valid, 2000-01-01 20:30:00 +0000
2015-08-27 16:03:35.673 Del Taco[1960:117431] ########### 2015-08-27 19:30:00 +0000
2015-08-27 16:03:35.674 Del Taco[1960:117431] new date: 8/27/15, 4:30 PM
I think I have this figured out. It was my date formatter where I set the format like this:
#"HH:mm a"
I went to Unicode's website to double check that I was doing this right, and ended up changing my format string to:
#"h:mm a"
And things seem to be working out well!

NSDateFormatter not converting to correct date

I have a problem converting a string date to NSDate since the conversion is not correct. This is my code:
NSString *stringDate = #"6/20/2014 8:38:52 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSDate *timeStamp = [dateFormatter dateFromString:stringDate];
The log always says TIMESTAMP: 2014-06-20 12:38:37 +0000.
How can I convert it to a correct date? Thanks in advance.
I believe you are doing this to display the date in the log:
NSLog(#"timeStamp = %#", timeStamp);
Instead keep the date formatter around (store it globally or something) and do:
NSLog(#"timeStamp = %#", [dateFormatter stringFromDate:timeStamp]);
The difference is the first line of code calls [NSDate description] to format the date, which uses UTC/GMT time zone, where as the second line of code uses the time zone configured in the date formatter (which by default is the same the locale's time zone), and crucially the same time zone you used to parse the string in the first place.
Add
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
And you get date in UTC time zone.
You can use this. It will give you proper output
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateComponents setYear:2014];
[dateComponents setMonth:6];
[dateComponents setDay:20];
[dateComponents setHour:8];
[dateComponents setMinute:38];
[dateComponents setSecond:52];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [calendar dateFromComponents:dateComponents];
//NSDate *timeStamp = [dateFormatter dateFromString:stringDate];
NSLog(#"date = %#",date);
//solutions[2247:70b] date = 2014-06-20 08:38:52 +0000 printing date

Date selected from UIDatePicker is different from the date being saved

This is how I setup my datePicker
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.timeZone = [NSTimeZone localTimeZone];
This is how I save the date that I selected
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
dateToSave = [formatter dateFromString:self.dateTextField.text];
NSLog(#"date saved = %#", dateToSave);
If I select Nov 18 2013 from the date picker, the NSLog shows
date saved = 2013-11-17 16:00:00 +0000
However, somewhere in my code, I need to get the difference in days between today's date and the date that I selected in the datepicker.
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:[NSDate date] toDate:dateSaved options:0];
NSLog(#"number of days => %i", [dateComponents day]);
Today is Nov 10. The date I saved is Nov 18. But the number of days difference is 7, instead of 8.
Your time zone is -8. 2013-11-17 16:00:00 +0000 equals to 2013-11-18 00:00:00 -0800.
Use [NSTimeZone timeZoneForSecondsFromGMT:0] instead of [NSTimeZone localTimeZone]
(This answer refers to the updated question about calculating the number of days
between two dates.)
The problem is that [NSDate date] is the current date+time, not the start of the current day. For example, if
[NSDate date] = "2013-11-10 10:00:00"
dateSaved = "2013-11-18 00:00:00" (both in your *local* timezone)
then the difference between
these two dates is "7 days and 14 hours". Therefore you get 7 as the number of days.
So you have to calculate the start of the current day first:
NSDate *startOfDay;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&startOfDay
interval:NULL
forDate:[NSDate date]];
and then use it in the calculation of the difference:
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
fromDate:startOfDay
toDate:dateSaved
options:0];
NSDateFormatter *date_form=[[NSDateFormatter alloc]init];
[date_form setDateFormat:#"dd/MM/yyyy"];
NSDate *seletected_date = [datepicker date];
NSString *dateToSave=[[NSString alloc] initWithFormat:#"%#",[date_form stringFromDate:seletected_date]];
NSLog(#"date saved = %#", dateToSave);
Remove localtimezone

Why does this NSDate gotten from NSString have the month switched?

Im sending a string to a dateFormatter with this code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"CST"]];
NSDate *currentDate = [NSDate date];
NSCalendar* calendario = [NSCalendar currentCalendar];
NSDateComponents* components = [calendario components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
//make new strings
NSString *adjustedOpenDateString = [NSString stringWithFormat:#"%#-%ld-%ld %#", #"2013", (long)[components month], (long)[components day], openDateString];
NSString *adjustedCloseDateString = [NSString stringWithFormat:#"%#-%ld-%ld %#", #"2013", (long)[components month], (long)[components day],closeDateString];
NSLog(#"adjustedString %#", adjustedCloseDateString); //<<<<---NSLOG1
//Convert strings to dates
NSDate *openDate = [dateFormatter dateFromString:adjustedOpenDateString];
NSDate *closeDate = [dateFormatter dateFromString:adjustedCloseDateString];
NSLog(#"BEFORE COMPONENTS open, now, close %#,%#,%#", openDate,[NSDate date], closeDate); //<<<<---NSLOG2
if ([self timeCompare:openDate until:closeDate]) {
NSLog(#"OPEN-timeCompare");
} else {
NSLog(#"CLOSED-timeCompare");
}
And I get the adjustedString NSLog logging the current date correctly:
adjustedString 2013-7-25 10:00 PM
But when I log the dates converted from strings, the month is lost...switched from july to jan
open, now, close 2013-01-25 13:00:00 +0000,2013-07-26 02:54:31 +0000,2013-01-26 04:00:00 +0000
Why does this happen?
Your format string is wrong, for month you have to use "MM", so replace:
[dateFormatter setDateFormat:#"yyyy-mm-dd hh:mm a"];
with
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm a"];
Take a look at Date Format Patterns, Unicode Technical Standard #35.
Switch your format string to #"yyyy-MM-dd hh:mm a" According to the Unicode Technical Standard #35, which NSDateFormatter uses for date format strings, lowercase 'm' is for minute and uppercase is for month.

IOS NSDateFormatter Problems

We are building an app which requires the storage of a date for an entry on the device, the app will be international so we hit two dilema's / challenges.
User Preferences
If the user chooses the 12 hour rahter than 24 hour format we are returned from [NSDate date] a date like this 2012-07-17 11:26:03 AM which for sorting in a SQLite database is less than optimal as we cannot store it as a date.
User Locale
Typically this is ok however here in blighty we have a wonderfult thing called british summertime. which adds one hour every October 25th - 30th in a cycle and removes one hour every March 25 - 31th in a cycle so if no adjustment is made for 8 months of the year the time is one hour behind.
What I need to achieve is a consistent date formatted like this: 2012-07-17 11:26:03 no matter where the device is located and also taking into account where GMT+1 comes into place.
Any help would be awesome.
EDIT*
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT+01:00"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSDate *localDate = [dateFormatter dateFromString:timeStamp];
NSLocale* currentLocale = [NSLocale currentLocale];
NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
NSLog(#"Country Code: %#", countryCode);
NSLog(#"Current Loacle: %#", currentLocale);
if(([countryCode isEqualToString: #"GB"])){
NSDate *mydate = [NSDate date];
NSDate *fiddlyFoo = [mydate dateByAddingTimeInterval:3600];
NSLog(#"Print GMT +1 %#",fiddlyFoo);
} else {
NSLog(#"Print GMT Local %#",localDate);
}
I'm doing something like this now. Note that NSDate "knows" about the current timezone and daylight savings time etc. So you just need to get the GMT version of the time in a sortable representation. I'd suggest RFC 3339 but you can use variations on it per your needs:
This code:
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
// Create a local date for London, for testing purposes
NSDateComponents *comps = [NSDateComponents new];
[comps setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/London"]];
[comps setDay:1];
[comps setMonth:7];
[comps setYear:2012];
[comps setHour:14];
NSDate *date = [gregorian dateFromComponents:comps];
// Just want to show this date is 2PM in London July 1st
NSDateFormatter *curFormat = [NSDateFormatter new];
[curFormat setDateStyle:NSDateFormatterFullStyle];
[curFormat setTimeStyle:NSDateFormatterFullStyle];
NSLog(#"Reference date is good no: %#", [curFormat stringFromDate:date]);
// So now we get the date as a rfc3339 string, referenced to GMT
NSString *timeString;
{
NSDateFormatter *rfc3339 = [NSDateFormatter new];
[rfc3339 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
rfc3339.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
timeString = [rfc3339 stringFromDate:date];
}
// referenced to UTC (sortable with any other time), can save in SQL DB etc
NSLog(#"Date as rfc3339 string: %#", timeString);
// Now lets convert it back into a BST time
NSDate *newDate;
{
NSDateFormatter *rfc3339 = [NSDateFormatter new];
[rfc3339 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
rfc3339.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
newDate = [rfc3339 dateFromString:timeString];
// we want to show this as a string 2012-07-17 11:26:03
NSDateFormatter *newFormatter = [NSDateFormatter new];
[newFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; // local time
[newFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/London"]];
NSLog(#"Local string using 24 hour clock: %#", [newFormatter stringFromDate:newDate]);
}
Generates this output, which I believe is what you want:
TimeTester[58558:f803] Reference date is good no: Sunday, July 1, 2012 9:00:00 AM Eastern Daylight Time
TimeTester[58558:f803] Date as rfc3339 string: 2012-07-01T13:00:00Z
TimeTester[58558:f803] Local string using 24 hour clock: 2012-07-01 14:00:00

Resources