【问题标题】:dynamic population to date timer from controller来自控制器的动态填充日期计时器
【发布时间】:2018-03-02 09:47:22
【问题描述】:

我已按照this tute 在页面上呈现计时器时钟,我接下来要做的是从我控制器中的值启动日期计时器。

计时器:

<div class="clock">
    <div id="Date"></div>
    <ul id= "dateUL">
        <li id="hours"></li>
        <li id="point">:</li>
        <li id="min"></li>
        <li id="point">:</li>
        <li id="sec"></li>
    </ul>
</div>

<style>

@@font-face {
    font-family: 'BebasNeueRegular';
    src: url('BebasNeue-webfont.eot');
    src: url('BebasNeue-webfont.eot?#iefix') format('embedded-opentype'),
         url('BebasNeue-webfont.woff') format('woff'),
         url('BebasNeue-webfont.ttf') format('truetype'),
         url('BebasNeue-webfont.svg#BebasNeueRegular') format('svg');
    font-weight: normal;
    font-style: normal;
}

.container {
    width: 60px;
    margin: 0 auto;
    overflow: hidden;
}

.clock {
    width: 250px;
    margin: 0 auto;
    padding: 30px;
    /*border: 1px solid #333;*/
    color: black;
}

#Date {
    font-family: 'BebasNeueRegular', Arial, Helvetica, sans-serif;
    font-size: 16px;
    text-align: center;
    /*text-shadow: 0 0 5px #00c6ff;*/
}

#dateUL {
    width: 180px;
    margin: 0 auto;
    padding: 0px;
    list-style: none;
    text-align: center;
}

#dateUL li {
    display: inline;
    font-size: 1em;
    text-align: center;
    font-family: 'BebasNeueRegular', Arial, Helvetica, sans-serif;
    /*text-shadow: 0 0 5px #00c6ff;*/
}

#point {
    position: relative;
    -moz-animation: mymove 1s ease infinite;
    -webkit-animation: mymove 1s ease infinite;
    padding-left: 10px;
    padding-right: 10px;
}

/* Simple Animation */
@@-webkit-keyframes mymove {
    0% {opacity: 1.0;
    /*text-shadow: 0 0 20px #00c6ff;*/
}

50% {
    opacity: 0;
    text-shadow: none;
}

100% {
    opacity: 1.0;
    /*text-shadow: 0 0 20px #00c6ff;*/
}   
}

@@-moz-keyframes mymove {
    0% {
        opacity: 1.0;
        /*text-shadow: 0 0 20px #00c6ff;*/
    }

    50% {
        opacity: 0;
        text-shadow: none;
    }

    100% {
        opacity: 1.0;
        /*text-shadow: 0 0 20px #00c6ff;*/
    }
}
</style>


<script type="text/javascript">
$(document).ready(function() {
// Create two variable with the names of the months and days in an array
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

// Create a newDate() object
var newDate = new Date();
// Extract the current date from Date object
newDate.setDate(newDate.getDate());
// Output the day, date, month and year
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());

setInterval( function() {
    // Create a newDate() object and extract the seconds of the current time on the visitor's
    var seconds = new Date().getSeconds();
    // Add a leading zero to seconds value
    $("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
    },1000);

setInterval( function() {
    // Create a newDate() object and extract the minutes of the current time on the visitor's
    var minutes = new Date().getMinutes();
    // Add a leading zero to the minutes value
    $("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
    },1000);

setInterval( function() {
    // Create a newDate() object and extract the hours of the current time on the visitor's
    var hours = new Date().getHours();
    // Add a leading zero to the hours value
    $("#hours").html(( hours < 10 ? "0" : "" ) + hours);
    }, 1000);
});
</script>

控制器:

 public TimeSpan currentTimeSpentInDay(int ENumber, string StartDate)
        {

        DateTime today = DateTime.Today.Date;
        DateTime dt = DateTime.Parse(StartDate);
        Calculations calc = new Calculations();
        List<Pair> PairList = new List<Pair>();
        PairList = calc.getSingleDevicePairs(EnrollNumber, dt, dt);
        List<DateAndTime> ts = calc.getTimeSpentEachDay(PairList);


        //getting the last Check-in of the day for the emp

        var lastPunch = (from d in db.Logs
                         where d.Id == ENumber && d.Date == today && d.CheckType == "I"
                         select d).Distinct().ToList();

        var lastCheckInDate = lastPunch.LastOrDefault();
        var lastCheckIn = lastCheckInDate.Time.TimeOfDay;
        DateTime currentDate = DateTime.Now;

         var curTime = Convert.ToDateTime(currentDate.TimeOfDay.ToString("hh\\:mm\\:ss")).TimeOfDay;

        var totalCurrent = curTime - lastCheckIn;



        if (ts.Count > 0)
        {
            var checkTime = ts[0].Time + totalCurrent;
            ViewBag.timeSpentToday = ts[0].Time + totalCurrent;

            return checkTime;
        }
        else
            return new TimeSpan(0, 0, 0);
    }

我尝试过的;

我向控制器发送了一个 ajax 调用以获取 hh:min:ss 中的时间

                      $.ajax({
                          url: baseUrl + 'Stats/currentTimeSpentInDay?EnrollNumber=' + event.id + '&StartDate=' + event.start.format('YYYY-MM-DD'),
                          contenttype: 'application/json',
                          data: '',
                          type: 'post'
                      }).done(function (data) {
                          console.log('current time: ' + data);                            
                      });

这得到了时间,但我不知道如何在时钟内填充它。

图片: enter image description here enter image description here

更新:

我更改了代码,但它在小时中添加了前导零,而不是触发秒。

初始化时:

        //timespent in day
    $.ajax({
        url: baseUrl + 'Stats/currentTimeSpentInDay?EnrollNumber=' + id + '&StartDate=' + e,
        contenttype: 'application/json',
        data: '',
        type: 'post'
    }).done(function (data) {
        console.log('KKcurrent time:', data);
        if(data != '')
        {
            var splitDate = data.split(':');

            console.log('0: ' + splitDate[0]);               
            console.log('1: ' + splitDate[1]);
            console.log('2: ' + splitDate[2]);

            $("#hours").html(splitDate[0]);
            $("#min").html(splitDate[1]);
            $("#sec").html(splitDate[2]);
        }       

    });

然后是时钟部分:

<script type="text/javascript">
$(document).ready(function() {
// Create two variable with the names of the months and days in an array
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

// Create a newDate() object
var newDate = new Date();
// Extract the current date from Date object
newDate.setDate(newDate.getDate());
// Output the day, date, month and year
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());

setInterval( function() {
    // Create a newDate() object and extract the seconds of the current time on the visitor's
    //var seconds = new Date().getSeconds();
    var seconds = document.getElementById("sec").innerText;
    // Add a leading zero to seconds value
    $("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
    },1000);

setInterval( function() {
    // Create a newDate() object and extract the minutes of the current time on the visitor's
    //var minutes = new Date().getMinutes();
    // Add a leading zero to the minutes value
    var minutes = document.getElementById("min").innerText;
    $("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
    },1000);

setInterval( function() {
    // Create a newDate() object and extract the hours of the current time on the visitor's
    //var hours = new Date().getHours();
    var hours = document.getElementById("hours").innerText;
    // Add a leading zero to the hours value
    $("#hours").html(( hours < 10 ? "0" : "" ) + hours);
    }, 1000);
});
</script>

enter image description here

【问题讨论】:

  • Sam,这个问题与页面元素的逻辑和功能有关,因此在这种情况下您可以省略 css,因为它仅用于设置样式。
  • 关于问题本身,您可以通过id 引用它们来更改每个元素的值,就像在setInterval() 上所做的那样。您要为其分配的值将出现在data 响应中。但是您的setInterval() 将在一秒钟后重置这些值,因为它们调用new Date(),这将返回一个带有当前时间的Date 对象,因此您的控制器返回的对象不会“粘住”。
  • @SamKay 你的 ajax 什么时候被调用?
  • @cosh 那我怎么让它“坚持”呢?
  • @Kumar_Vikas 在函数内调用的事件上,但我也可以在开始时调用它,没问题。问题是将它嵌入到时钟中

标签: c# asp.net-mvc date real-time-clock


【解决方案1】:

使用Split() 拆分您的结果。然后将其分配给各自的div's

                    $.ajax({
                              url: baseUrl + 'Stats/currentTimeSpentInDay?EnrollNumber=' + event.id + '&StartDate=' + event.start.format('YYYY-MM-DD'),
                              contenttype: 'application/json',
                              data: '',
                              type: 'post'
                          }).done(function (data) {
                                 if(data !='')
                                 {
                                    var splitDate = data.split(':');
                                    $("#hours").html(splitDate[0]);
                                    $("#min").html(splitDate[1]);
                                    $("#sec").html(splitDate[2]);
                                 }                      
                          });

【讨论】:

  • 未捕获的类型错误:$(...).split 不是函数
  • 只需data.split(':') 即可。检查更新的答案。
猜你喜欢
  • 1970-01-01
  • 2020-01-11
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 2016-10-26
  • 2014-10-20
相关资源
最近更新 更多