iOS 某格式日期替换成另一种格式日期

来源:互联网 发布:xp设置网络打印机 编辑:程序博客网 时间:2024/04/29 06:42

当工作需要为用户提供选择不同格式日期的功能,为同事写一个转换日期格式的CustomTimeLabel··· 虽然很简单,但是还是想写在博客里,以备不时之需~


继承于UILable的CustomTimeLabel

一个实例方法

- (void)setLabelWithText:(NSString *)text inputFormat:(NSString *)inputFormat outputFormat:(NSString *)outputFormat{    if ([inputFormat isEqualToString:@"timeStemp"]) {        NSTimeInterval time = [text doubleValue];        if (text.length == 13) {            time = [text doubleValue] / 1000;        }        NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];                //实例化一个NSDateFormatter对象        NSDateFormatter *dateFormatter  = [[NSDateFormatter alloc]init];        [dateFormatter setDateFormat:outputFormat];                NSString *dateStr = [dateFormatter stringFromDate:detailDate];        self.text = dateStr;    }    else    {        NSDateFormatter *informat = [[NSDateFormatter alloc]init];        [informat setDateFormat:inputFormat];        NSDate *date = [informat dateFromString:text];        NSDateFormatter *outformat = [[NSDateFormatter alloc]init];        [outformat setDateFormat:outputFormat];        self.text = [outformat stringFromDate:date];    }}

其中inputFormat是变化之前的格式

“timeStemp”是时间戳格式的时间,

“yyyy-MM-dd”是普通时间格式。


outputFormat是变化之后的格式


使用:

    CustomTimeLabel *label = [[CustomTimeLabel alloc]initWithFrame:CGRectMake(0, 100, kScreenW, 20)];    [label setLabelWithText:@"14708980" inputFormat:@"timeStemp" outputFormat:@"yyyy-MM-dd HH:mm:ss"];    [self.view addSubview:label];        CustomTimeLabel *label1 = [[CustomTimeLabel alloc]initWithFrame:CGRectMake(0, 200, kScreenW, 20)];    [label1 setLabelWithText:@"20160305" inputFormat:@"yyyyMMdd" outputFormat:@"yyyy年MM月"];    [self.view addSubview:label1];



0 0
原创粉丝点击