Comparing 2 times with jquery

纵饮孤独 提交于 2019-12-13 07:43:40

问题


Thanks in advance for any help...

I'm trying to (1) generate a begin time and end time for a form, (2) find the difference between the two, and (3) add the difference to a new input.

Here's what I have so far:

<a href="#" id="starttime">Begin time</a>
<input id="starttimeinput" name="starttimeinput" type="text" value="">
<script>
    $("#starttime").click(function () {
         var begintime = event.timeStamp;
         $("#starttimeinput").val(begintime);
    });
</script>
<a href="#" id="endtime">end time</a>
<input id="endtimeinput" name="endtimeinput" type="text" value="">
<script>
    $("#endtime").click(function () {
         var endtime = event.timeStamp;
         $("#endtimeinput").val(endtime);
    });
</script>
<input id="totaltime" name="totaltime" type="text">
<script>
    $("#totaltime").focus(function () {
       var begintime = $("#starttimeinput").val();
       var endtime = $("#endtimeinput").val();
       var totaltime = endtime - begintime;
       $("#totaltime").val(totaltime); 
     });     
</script>

The first part works (entering the timestamps into the beginning time and end time inputs). I've never worked with numbers before and can't figure out the second part. The result that comes up is "NaN".

Also this might be useful to know the the time between when the links are clicked should be around 30 seconds...

Thanks much for any help you guys have answered so many questions of mine without me having to post!


回答1:


You need to parseInt() the times back out, otherwise they're just strings (as returned by .val()).

$("#totaltime").focus(function () {
    var begintime = parseInt($("#starttimeinput").val(), 10),
        endtime = parseInt($("#endtimeinput").val(), 10),
        totaltime = endtime - begintime;
    $("#totaltime").val(totaltime); 
 });

Personally, I'd sooner just store the begintime and endtime values myself, rather than in text inputs (why does the user need to see them, anyway?). Like this:

var begintime,
    endtime;
$("#starttime").click(function (event) {
     begintime = event.timeStamp;
     //$("#starttimeinput").val(begintime);
});

$("#endtime").click(function (event) {
     endtime = event.timeStamp;
     //$("#endtimeinput").val(endtime);
});

$("#totaltime").focus(function () {
    $("#totaltime").val(endtime - begintime); 
});

On a side note, I would recommend moving your jQuery code out of inline <script> tags and into an external JS file. This makes for more maintainable markup and JS. Just wrap all of your JS code in a document ready handler:

$(document).ready(function () {
    /* your code here */
});

or, more concisely,

$(function () {
    /* your code here */
});


来源:https://stackoverflow.com/questions/4929604/comparing-2-times-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!