美文网首页
真实时间倒计时

真实时间倒计时

作者: RichMartin | 来源:发表于2021-05-11 17:01 被阅读0次
    QQ截图20210511170042.png
    using System;
    using UnityEngine.UI;
    
    public class CountDownTimer
    {
        bool _timerIsRunning = false;
        Text timeText;
        DateTime daysLeft;
        Action action;
    
        public CountDownTimer(Text text,double day=0, double hour = 0, double min = 0, double sec = 0, Action ac = null)
        {
            daysLeft = DateTime.Now.AddDays(day).AddHours(hour).AddMinutes(min).AddSeconds(sec);
            action = ac;
            timeText = text;
        }
     
        public void TimerStart()
        {
            _timerIsRunning = true;
        }
    
        public void TimerStop()
        {
            _timerIsRunning = false;
        }
    
        public void Update()
        {
            if (_timerIsRunning)
            {
                DateTime startDate = DateTime.Now;
                var ts = daysLeft - startDate;
                if (ts < TimeSpan.Zero)
                {
                    _timerIsRunning = false;
                    action?.Invoke();
                    return;
                }
                float days = ts.Days;
                float hour = ts.Hours;
                float minutes = ts.Minutes;
                float seconds = ts.Seconds;
                timeText.text = string.Format("{0}天{1:00}:{2:00}:{3:00}", days, hour, minutes, seconds);
            }
        }
    }
    
    
    
    
        var timer = new CountDownTimer(text, day, hour, min, sec);
            timer.TimerStart();
    

    相关文章

      网友评论

          本文标题:真实时间倒计时

          本文链接:https://www.haomeiwen.com/subject/rtkndltx.html