私のコードからデータ フォーマッタを操作する例をいくつか示します。これらの関数のいずれかを使用して、フォーマットに合わせて微調整できるはずです。
利用方法
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [Constants getTitleDateFormatter];
NSString *dateString = [dateFormatter stringFromDate:today];
[dateFormatter release];
機能
+ (NSDateFormatter *) getDateFormatterWithTimeZone {
//Returns the following information in the format of the locale:
//YYYY-MM-dd HH:mm:ss z (Z is time zone)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
return dateFormatter;
}
+ (NSDateFormatter *)dateFormatterWithoutYear {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:@"/yy" withString:@""];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingCharactersInRange:secondSpace withString:@""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) dateFormatterMonthDayOnly {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:@"/yy" withString:@""];
NSRange range;
range.location = 0;
range.length = 3;
format = [format substringWithRange:range];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) getTitleDateFormatter {
//Returns the following information in the format of the locale:
//MM-dd-yyyy hh:mm:ssa
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *format = [dateFormatter dateFormat];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
format = [format stringByReplacingCharactersInRange:secondSpace withString:@""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}