用字符串实现倒计时

本文介绍了电商平台中利用字符串实现倒计时的方法,详细讲解了如何根据活动的开始和结束时间、库存情况更新倒计时显示,并讨论了这种方法在用户修改手机时间时可能存在的精度问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

博主是做电商平台的,电商一定有的限时秒杀业务对倒计时的时间要求特别精准,因此,我们就要取得相对精准的时间,我准备分为一个系列文章来介绍此方法。

一、用字符串实现倒计时;

      用字符串做倒计时,从接口取的是活动开始时间和结束时间,逻辑如下:

#1 倒计时逻辑--伪代码

###status == 1时,商品上线
 
    if (status == 1)  // 已上线.
    {
       if(开始时间 - 当前时间 < 0)
       {
              if (结束时间 - 当前时间 > 0)
              {
                     if (库存 > 0)
                     {
                           timeLabel.text = @"距结束:1天1时1分1秒";
                           button.text = @"立即抢购";
                           buttton.enable = YES;
                     }
                     else  //库存 < 0
                     {
                           timeLabel.text = @"距结束:1天1时1分1秒";
                           button.text = @"已抢光";
                           button.enable = NO;
                     }
              }
              else if (结束时间 - 当前时间 = 0)
              {
                     _tagStatus == 2; 或者 重新发网络请求更新数据;
              }
              else if (结束时间 - 当前时间 < 0)
              {
                     timeLabel.text = @"活动已经结束";
                     button.text = @"活动结束";
                     button.enable = NO;
              }
              
        }
        else if (开始时间 - 当前时间 == 0)
        {
              //令 _tagStatus == 1;  或者 重新发网络请求更新数据;
        }
        else if (开始时间 - 当前时间 >= 0) //手机时间比当前时间慢了。
        {
              timeLabel.text = @"距开始:0天0时0分0秒";
              button.enable = NO;
              button.text = @"即将开始";
        }     


    }
###status == 0时,未上线
    if (status == 0)
    {
             if (开始时间 - 当前时间 > 0)
             {
                  timeLabel.text = @"距开始:1天1时1分1秒"; 
                  button.enable = NO;
                  button.text = @"即将开始";
             }
             if (开始时间 - 当前时间 == 0)
             { 
                 令 _tagStatus == 1;  或者 重新发网络请求更新数据;
             }
             else if (开始时间 - 当前时间 < 0)
             {
                  printf("活动还没开始,手机时间比标准时间快了");
             }
    }
###status == 2时,已下线
    if (status == 2)
    {
            timeLabel.text = @"已经下线";
            button.enable = No;
            button.text = @"已经下线";
            [self.timer invalidate];
            
    }
    

然而,在此方法中,由于比较的当前时间为手机或者系统本地的时间,这样当用户恶意串改手机时间时,会导致时间的不精准。不过对时间要求不那么严密的倒计时,可以用此方法。实现代码参考如下:

#pragma mark -- 利用返回的字符串时间做

//=====================================利用字符串时间做=====================================

-(void)doSth

{

    //NSLog(@"_tagStatus:%@",_tagStatus);

    

    NSInteger statusInt = [_tagStatus integerValue];//上线状态

    NSInteger repertoryInt = [_repertory integerValue];//库存

    

    

    NSArray *startArr = [self FormatterTheString:_timeStrStart];

    NSArray *endArr = [self FormatterTheString:_timeStrEnd];

    

    NSString *startStr = [NSString stringWithFormat:@"距开始:%@%@%@%@",startArr[0],startArr[1],startArr[2],startArr[3]];

    NSString *endStr = [NSString stringWithFormat:@"距结束:%@%@%@%@",endArr[0],endArr[1],endArr[2],endArr[3]];

    if ([startArr[3] integerValue] < 10)

    {

        startStr = [NSString stringWithFormat:@"距开始:%@%@%@0%@",startArr[0],startArr[1],startArr[2],startArr[3]];

    }

    if ([endArr[3] integerValue] < 10)

    {

        endStr = [NSString stringWithFormat:@"距结束:%@%@%@0%@",endArr[0],endArr[1],endArr[2],endArr[3]];

    }

    

    NSInteger ddd1 = [startArr[0] integerValue];

    NSInteger hhh1 = [startArr[1] integerValue];

    NSInteger mmm1 = [startArr[2] integerValue];

    NSInteger sss1 = [startArr[3] integerValue];

    

    NSInteger ddd2 = [endArr[0] integerValue];

    NSInteger hhh2 = [endArr[1] integerValue];

    NSInteger mmm2 = [endArr[2] integerValue];

    NSInteger sss2 = [endArr[3] integerValue];


//*********************新的逻辑*********************

    if (statusInt == 1)// 已上线.

    {

        if (ddd1>=0 && hhh1>=0 && mmm1>=0 && sss1>=0)//开始时间 - 当前时间 > 0,手机时间比当前时间慢了。

        {

            self.timeLabel.text = startStr;

            self.buyBtn.enabled = NO;

            [self.buyBtn setBackgroundColor:UIColorFromOXRGB(0xAFAEAE)];

            [self.buyBtn setTitle:@"即将开始" forState:UIControlStateNormal];

        }

        else if (ddd1==0 && hhh1==0 && mmm1==0 && sss1==0) //开始时间 - 当前时间 = 0

        {

            

        }

        else  //开始时间 - 当前时间 < 0,活动已经开始

        {

            if (ddd2>=0 && hhh2>=0 && mmm2>=0 && sss2>=0) //活动已经开始,还没结束。

            {

                if (repertoryInt > 0)//库存足够

                {

                    self.timeLabel.text = endStr;

                    _buyBtn.enabled = YES;

                    [self.buyBtn setBackgroundColor:UIColorFromOXRGB(0xFF4351)];

                    [self.buyBtn setTitle:@"立即抢购" forState:UIControlStateNormal];

                }

                else //库存不够了。已抢光。

                {

                    self.timeLabel.text = endStr;

                    self.buyBtn.enabled = NO;

                    [self.buyBtn setBackgroundColor:UIColorFromOXRGB(0xAFAEAE)];

                    [self.buyBtn setTitle:@"已抢光" forState:UIControlStateNormal];

                }

                

            }

            else if (ddd2==0 && hhh2==0 && mmm2==0 && sss2==0)//活动即将结束,把活动状态置为2.

            {

                //// _tagStatus == 1;  或者 重新发网络请求更新数据;

                _tagStatus = @"2";

                //创建通知

//                NSNotification *notification =[NSNotification notificationWithName:@"daojishi" object:self userInfo:nil];

//                //通过通知中心发送通知

//                [[NSNotificationCenter defaultCenter] postNotification:notification];

                

                

            }

            else  //结束时间-当前时间<0

            {

                self.timeLabel.text = @"活动已经结束";

                self.buyBtn.enabled = NO;

                [self.buyBtn setBackgroundColor:UIColorFromOXRGB(0xAFAEAE)];

                [self.buyBtn setTitle:@"活动结束" forState:UIControlStateNormal];

                [self.timer invalidate];

            }

        }

    }

    else if (statusInt == 0//未上线

    {

        if (ddd1>=0 && hhh1>=0 && mmm1>=0 && sss1>=0)//开始时间 - 当前时间 > 0

        {

            self.timeLabel.text = startStr;

            self.buyBtn.enabled = NO;

            [self.buyBtn setBackgroundColor:UIColorFromOXRGB(0xAFAEAE)];

            [self.buyBtn setTitle:@"即将开始" forState:UIControlStateNormal];

        }

         else if (ddd1==0 && hhh1 ==0 && mmm1==0 && sss1==0)//开始时间 - 当前时间 = 0

        {

            // _tagStatus == 1;  或者 重新发网络请求更新数据;

            //_tagStatus = @"1";

            //创建通知

            NSNotification *notification =[NSNotification notificationWithName:@"daojishi" object:self userInfo:nil];

            //通过通知中心发送通知

            [[NSNotificationCenter defaultCenter] postNotification:notification];

            

        }

        else //开始时间 - 当前时间 < 0

        {

            //活动还没开始,手机时间快了。

            

        }

    }

    else if (statusInt == 2)

    {

        self.timeLabel.text = @"活动已下线";

        self.buyBtn.enabled = NO;

        [self.buyBtn setBackgroundColor:UIColorFromOXRGB(0xAFAEAE)];

        [self.buyBtn setTitle:@"活动下线" forState:UIControlStateNormal];

        [self.timer invalidate];

    }

    

}



- (NSArray *)FormatterTheString:(NSString *)string

{

    NSString *str = [[NSString alloc]init];

    NSArray *arr = [[NSArray alloc]init];

    

    BOOL timeStart = YES;

    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象

    NSDateComponents *endTime = [[NSDateComponents alloc] init];    //初始化目标时间...

    NSDate *today = [NSDate date];    //得到当前时间

    //NSLog(@"date:%@",[today description]);

    

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *dateString = [dateFormatter dateFromString:string];

    NSString *overdate = [dateFormatter stringFromDate:dateString];

    

    static int year;

    static int month;

    static int day;

    static int hour;

    static int minute;

    static int second;

    

    if(timeStart)

    {

    //NSDate中取出年月日,时分秒,但是只能取一次

        year = [[overdate substringWithRange:NSMakeRange(0, 4)] intValue];

        month = [[overdate substringWithRange:NSMakeRange(5, 2)] intValue];

        day = [[overdate substringWithRange:NSMakeRange(8, 2)] intValue];

        hour = [[overdate substringWithRange:NSMakeRange(11, 2)] intValue];

        minute = [[overdate substringWithRange:NSMakeRange(14, 2)] intValue];

        second = [[overdate substringWithRange:NSMakeRange(17, 2)] intValue];

        timeStart= NO;

    }

    

    [endTime setYear:year];

    [endTime setMonth:month];

    [endTime setDay:day];

    [endTime setHour:hour];

    [endTime setMinute:minute];

    [endTime setSecond:second];

    NSDate *overTime = [cal dateFromComponents:endTime]; //把目标时间装载入date

    //用来得到具体的时差,是为了统一成北京时间

    unsigned int unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay| NSCalendarUnitHour| NSCalendarUnitMinute| NSCalendarUnitSecond;

    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:overTime options:0];

    NSString *t = [NSString stringWithFormat:@"%ld", (long)[d day]];

    NSString *h = [NSString stringWithFormat:@"%ld", (long)[d hour]];

    NSString *fen = [NSString stringWithFormat:@"%ld", (long)[d minute]];

    NSString *miao = [NSString stringWithFormat:@"%ld", (long)[d second]];

    

    

    str = [NSString stringWithFormat:@"距开始:%@%@%@%@",t,h,fen,miao];

    arr = @[t,h,fen,miao];

    


    

    return arr;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值