Category使用实例,格式化时间
程序员文章站
2022-04-30 10:02:17
...
// // NSDateCategory.h // WebGameIphone // // Created by apple on 12-1-9. // Copyright 2012年 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDate (NSDateCategory) // 根据格式化样式得到时间字符串 - (NSString *)stringWithFormat:(NSString*)fmt; // 根据字符串和格式化样式得到时间 + (NSDate *)dateFromString:(NSString*)str withFormat:(NSString*)fmt; // 改变时间字符串格式化样式 + (NSString *)dateStringReplaceFormat:(NSString*)str oldFormat:(NSString*)fmt newFormat:(NSString*)n_fmt; @end @implementation NSDate (NSDateCategory) - (NSString *)stringWithFormat:(NSString *)fmt { static NSDateFormatter *fmtter; if (fmtter == nil) { fmtter = [[NSDateFormatter alloc] init]; } if (fmt == nil || [fmt isEqualToString:@""]) { fmt = @"HH:mm:ss"; } [fmtter setDateFormat:fmt]; return [fmtter stringFromDate:self]; } + (NSDate *)dateFromString:(NSString *)str withFormat:(NSString *)fmt { static NSDateFormatter *fmtter; if (fmtter == nil) { fmtter = [[NSDateFormatter alloc] init]; } if (fmt == nil || [fmt isEqualToString:@""]) { fmt = @"HH:mm:ss"; } [fmtter setDateFormat:fmt]; return [fmtter dateFromString:str]; } + (NSString *)dateStringReplaceFormat:(NSString*)str oldFormat:(NSString*)fmt newFormat:(NSString*)n_fmt { NSDate *n_date = [NSDate dateFromString:str withFormat:fmt]; return [n_date stringWithFormat:n_fmt]; } @end