Reputation: 8608
I am pulling information from a database that contains dates formatted weird.
When they are pulled they are in the format of:
DayOfWeek, Month Date
I am attempting to use EventKit to have the option to add the date to the users calendar.
I can't seem to find the best way to go about doing this.
Any help or point in the right direction would be very much appreciated!!
Upvotes: 1
Views: 342
Reputation: 90117
Your problem is that this database has ambiguous dates. It does not have a year information. NSDateFormatters don't guess date information. They create dates from the information you provide. And since this information is missing the year will be 1970 (as in: the same year as the reference data).
Because the format that is saved in the database is totally stupid I assume that those dates always are within the next 365 days. So in theory you wouldn't have to save a year info.
You could then use something like this to figure out the NSDate from that totally ambiguous date information.
The idea is to transfer the date from 1970 (created from your string) to the current year. And if it would be in the past for current year (e.g. today is 31 March a date with "Foo, March 30" would be in the past) move it to next year.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE, MMMM d";
// the following line is important if you want that your code runs on device that are not english!
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDate *date = [dateFormatter dateFromString:@"Wednesday, March 30"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
NSDateComponents *todayComponent = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
NSInteger proposedYear = [todayComponent year];
// if supposed date would be in the past for the current year move it into next year
if ([components month] < [todayComponent month]) {
proposedYear++;
}
if ([components month] == [todayComponent month] && [components day] < [todayComponent day]) {
proposedYear++;
}
[components setYear:proposedYear];
date = [calendar dateFromComponents:components];
// just for logging, so you are sure that you use the correct year:
[dateFormatter setDateFormat:@"EEEE, MMMM d yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:date]);
Upvotes: 1
Reputation: 16725
You want to use an NSDateFormatter
:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE, MMMM d";
NSDate *date = [dateFormatter dateFromString:@"Tuesday, March 3"];
"DayOfWeek, Month Date" is ambiguous, so I did my best to guess what you meant. If I was wrong, you'll need to change the format string a bit. Here is a reference on the strings you can use.
Upvotes: 3