A beginner's problem, but I was wondering if anyone could help me with this:
I need to set four strings according to a string which contains a certain date (e.g. @"Apr 7, 2011"):
@"Thu"
@"7"
@"April"
@"2011"
So far, I found this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
NSLog(@"Date for locale %@: %@",
[[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);
// Output:
// Date for locale en_US: Jan 2, 2001
So this would give me a certain formatted date. I was wondering, however, how I can access certain parts of this date. There is the - (NSArray *)weekdaySymbols but I have no idea how to work this one and the documentation is quite frugal.
Any hints from calendar experts would be very welcome.
EDIT:
I guess this is part of the solution:
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
NSString *gbFormatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM" options:0 locale:gbLocale];
NSLog(@"gbFormatterString: %@", gbFormatString);
// Output: gbFormatterString: EEE d MMM, e.g. Thu 7 Apr
n.evermind,
You're going to need something like this:
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MMM dd, yyy"];
date = [formatter dateFromString:@"Apr 7, 2011"];
NSLog(@"%@", [formatter stringFromDate:date]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
NSInteger month=[components month]; // if necessary
NSInteger day = [components day];
NSInteger weekday = [components weekday]; // if necessary
NSDateFormatter *weekDay = [[[NSDateFormatter alloc] init] autorelease];
[weekDay setDateFormat:@"EEE"];
NSDateFormatter *calMonth = [[[NSDateFormatter alloc] init] autorelease];
[calMonth setDateFormat:@"MMMM"];
NSLog(@"%@ %i %@ %i", [weekDay stringFromDate:date], day, [calMonth stringFromDate:date], year );
output
2011-04-07 12:49:23.519 test[7296:207] Apr 07, 2011
2011-04-07 12:49:23.521 test[7296:207] Thu 7 April 2011
Cheers, Jordan
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With