hey i have my date as "7/30/2010". How do i print it as only the Month and Date ie. "7/30" I tried using NSFormatter but it prints my current date and not which is present in my database.
A:
You could add some utility methods for NSDate
.
Here is a sample header:
@interface NSDate (Utilities)
+ (NSDate *) customDateForString:(NSString *)dateString;
+ (NSDateFormatter *) customDateFormatter;
@end
The implementation:
@implementation NSDate (Utilities)
static NSDateFormatter *customDateFormatter = nil;
+ (NSDateFormatter *) customDateFormatter {
// Example: 7/30
if (!customDateFormatter) {
customDateFormatter = [[NSDateFormatter alloc] init];
[customDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[customDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
// cf. http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
[customDateFormatter setDateFormat:@"M/d"];
}
return customDateFormatter;
}
+ (NSDate *) customDateForString:(NSString *)dateString {
return [[self customDateFormatter] dateFromString:dateString];
}
@end
Whenever you need to parse a date string, you would call it like so:
NSLog(@"Parsed date: %@", [NSDate customDateForString:@"7/30/2010"]); // Parsed date: 7/30
Alex Reynolds
2010-07-30 10:50:27
A:
NSDate *date = dateFromYourDataBase;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"M/dd"];
NSLog(@"%@", [formatter stringFromDate:date]);
[formatter release];
jamapag
2010-07-30 11:00:41
-1. That will return `07/30` for the sample input.
Alex Reynolds
2010-07-30 11:03:30
hey it gives me warning: Initialization form incompatible pointer type. Is this because my data in database is stored as text?
2010-07-30 11:06:37
<<That will return 07/30 for the sample input>><<How do i print it as only the Month and Date>>My code print Month and Day2user391301: Yes, You need to convert your NSString to NSDate first
jamapag
2010-07-30 11:43:55
Your code which was: `@"MM/dd"` prints two characters for the month and day, even if the month and day values are a single digit. The right format would be `@"M/d", to print single digit values without padding.
Alex Reynolds
2010-07-30 11:59:30
hey thankss Jamapag.
2010-07-30 13:52:52