0

I have followed this tute to render a timer clock on the page, what I am trying to do next is to start the date timer from the values I have in my controller.

Timer:

<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>

Controller:

 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);
    }

What I tried;

I sent an ajax call to controller to fetch the time in 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);                            
                      });

this gets the time but I do not know how to populate it within the clock.

Pictures: enter image description here enter image description here

UPDATED:

I changed the code but it is adding leading zeros to hours instead of triggering the seconds.

On initialize:

        //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]);
        }       

    });

Then the clock part:

<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, this question relates to the logic and functionality of the page's elements, so you could omit the css in this case, as that only serves to style them. – cosh Mar 02 '18 at 10:00
  • About the question itself, you change the values of each element by referencing them by their [id](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById), just as you do on the `setInterval()`'s. The values you want to assign them will be present in the `data` response. But your `setInterval()`'s will reset these values after a second, because they call `new Date()`, which will return a `Date` object with the current time, so the one returned by your controller won't 'stick'. – cosh Mar 02 '18 at 10:12
  • @SamKay when is your ajax called? – Kumar_Vikas Mar 02 '18 at 10:26
  • @cosh how d I make it 'stick' then? –  Mar 02 '18 at 10:32
  • @Kumar_Vikas on an event called within a function, but I can call it in the beginning too, no issue. the problem is to embed it into the clock –  Mar 02 '18 at 10:32
  • @SamKay you need to alter your interval logic. So instead of, every second, altering the date to the current time (as in, whatever time is now), they need to alter it so that it's aligned to whatever your ajax request's response . You could, for example, have a single interval that every second executes the ajax request and updates the displayed time accordingly. – cosh Mar 02 '18 at 10:35
  • @cosh I know, but how do I separate the hh:mm:ss in my ajax resulted data? –  Mar 02 '18 at 10:36
  • @SamKay I don't understand what you're asking. the ajax response callback is a function just like the intervals callback functions. The code is the same, just inside the same block. Or are you talking about the `data` object structure? If that's the case, by logging the object, as you're doing, you should see where and how each of the fields (seconds, minutes and hours) are represented inside the object. Or alternatively, you could change your controller to return a `Json` with a custom response text, and, in that case, you can put each of the fields however you want. – cosh Mar 02 '18 at 10:44

1 Answers1

0

Split your result using Split(). Then assign it to the respective 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]);
                                 }                      
                          });
Kumar_Vikas
  • 837
  • 7
  • 16