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

当工作需要为用户提供选择不同格式日期的功能,为同事写一个转换日期格式的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];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值