JavaScript/jQuery: Subtract hours and minutes [duplicate] - javascript

This question already has answers here:
how to convert the minutes into hours and minutes with subtracted time(subtracted time values)
(4 answers)
Closed 4 years ago.
What I have:
Three time inputs consisting of a start time, end time and the difference between the two.
<input type="time" name="starttime" id="starttime">
<input type="time" name="endtime" id="endtime">
<input type="time" name="duration" id="duration" disabled>
What I need:
When the start or end time changes, the difference shows in the third input.
e.g. 23:15 - 20:00 = 03:15.
What I've tried:
So far, I can only produce the correct hours but not the minutes.
<script>
jQuery(document).ready(function($) {
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
// Attempt 1: Only gets hours.
//var difference_as_hours = difference / 60 / 60 / 1000;
//alert("Hour Difference: " + difference_as_hours);
// Attempt 2: Nothing happens.
//var difference_as_hours_and_minutes = difference.getHours() + ":" + difference.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_and_minutes);
// Attempt 3: Nothing happens.
//var difference_as_date = new Date("01/01/2007 " + difference);
//var difference_as_hours_and_minutes = difference_as_date.getHours() + ":" + difference_as_date.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_minutes);
// Attempt 4: Nothing happens.
var formatted_time = time_format(difference);
alert(formatted_time);
}
$("#starttime, #endtime").change(calculateTime);
calculateTime();
});
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? "0" + n : n;
}
</script>
How can I produce the hours and minutes?

Check below working Demo using momentjs:
let valuestart = moment.duration("20:00", "HH:mm");
let valuestop = moment.duration("23:15", "HH:mm");
let difference = valuestop.subtract(valuestart);
console.log(difference.hours() + ":" + difference.minutes())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

You try
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
var time = msToTime(difference);
console.log(time);
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
$("#starttime, #endtime").change(calculateTime);

Related

Call a Javascript function every second with setInterval

I try to get the function for my JavaScript countdown running every second but somehow I don't get the setInterval function to work.
This is how the JS code looks so far:
// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";
// Get date and time of today
var today = new Date();
// Calculate date and time difference
function getTimeDifference(endtime) {
var total = Date.parse(endtime) - Date.parse(today);
var seconds = Math.floor((total/1000) % 60);
var minutes = Math.floor((total/1000/60) % 60);
var hours = Math.floor((total/1000/60/60) % 24);
var days = Math.floor(total/1000/60/60/24);
return {
total,
days,
hours,
minutes,
seconds
};
}
function runCountdown() {
var t = getTimeDifference(endTimeDate);
document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}
window.setInterval(runCountdown, 1000);
The reason your code is not working as expected because you're declaring today outside of the function which means it's called only once , hence the diff result will always be the same. You probably want to move the assignment and the declaration of var today = new Date(); inside the getTimeDifference function so there will be an actual difference between the enddate value and the today value.
// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";
// Get date and time of today
// Calculate date and time difference
function getTimeDifference(endtime) {
var today = new Date();
console.log(endtime);
var total = Date.parse(endtime) - Date.parse(today);
var seconds = Math.floor((total/1000) % 60);
var minutes = Math.floor((total/1000/60) % 60);
var hours = Math.floor((total/1000/60/60) % 24);
var days = Math.floor(total/1000/60/60/24);
return {
total,
days,
hours,
minutes,
seconds
};
}
function runCountdown() {
var t = getTimeDifference(endTimeDate);
document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}
window.setInterval(runCountdown, 1000);
<div id="days">
</div>
<div id="hours">
</div>
<div id="minutes">
</div>
<div id="seconds">
</div>

How do i subtract End Time from Start Time without having negative minutes in Javascript timer

I need to subtract end time from start time to create a count down timer, I also want to avoid getting negative minutes. how do I do this.
var timeStart = new Date().getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();
var timeStartMin = new Date().getMinutes();
var timeEndMin = new Date("01/01/2007 " + valuestop).getMinutes();
var difference = timeEnd - timeStart;
var differenceMin = timeEndMin - timeStartMin;
the timer works fine, but VAR differenceMin is negative
I did not understand why you are getting differences between start and end because mostly for countdowns we use end-time and now difference. But anyway I am sending what you want and if you want you can use this function to get a difference between end and now too.
var getTimeDifference=function(from,to){
var difMs = (from - to);
if(difMs<=0){
return 0 + " days, " + 0 + " hours, " + 0 + " mins";
}else{
var difDays = Math.floor(difMs / 86400000);
var difHrs = Math.floor((difMs % 86400000) / 3600000);
var difMins = Math.round(((difMs % 86400000) % 3600000) / 60000);
return diffDays + " days, " + difHrs + " hours, " + diffMins + " mins";
}
}
var startTime= new Date('12-30-2019 20:00:00');
var endTime= new Date('11-1-2019 16:00:00');
getTimeDifference(endTime,startTime);

How to calculate the time difference using java script?

I'm getting date from the API in this format 14:30:00 inside "this.StartTime". My question is how can I calculate the time difference between the date I'm getting inside "this.StartTime" and present date?
Following is my component.ts code:-
getBookingDetails() {
this._CounsellingService.getBookingDetails().subscribe(
response => {
this.sessionDetails = response;
this.StartTime = this.sessionDetails.StartTime;
}
);
}
You can create a date today and then set its time part as startDate. Then compare it with current time;
var startTime = "14:30:00".split(":");
var h = startTime[0];
var m = startTime[1];
var s = startTime[2];
var now = new Date();
startTime = new Date(now);
startTime.setHours(h);
startTime.setMinutes(m);
startTime.setSeconds(s);
difference = startTime.getTime() - now.getTime();
console.log(msToTime(difference))
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}

Adding one minute to current time in Javascript

I use Date object to create time in my Javascript code and it should be formated like so : 08:04:21. This is how I tried to do it:
$('#time').click(function(){
var currentTime = new Date();
var Time=currentTime.getHours() + ":"
+ currentTime.getMinutes() + ":"
+ currentTime.setSeconds(currentTime.getSeconds() + 60);
console.log(Time);
$(this).val(Time);
});
But when Time is logged in console string looks like this 8:1:1467844916075. Same happens when i try this:
var Time=currentTime.getHours() + ":"
+ currentTime.setMinutes(currentTime.getMinutes() + 1) + ":"
+ currentTime.getSeconds();
It bring out similar result : 8:1467844916075:3. I even tried this answer: javascript add one minute to time object
$('#time').click(function(){
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
$(this).val(Time);
});
But Time in this case looks like this: 1467785566719. Any idea how to get human readable current time(not date) plus one minute?
You can check this:
Date.getTime() returns you the number of milliseconds since 1970/01/01.
So just grab it and add 1 minute to it to form new milliseconds count for new date.
var d = new Date();
var millisecondssince1970 = d.getTime();
var newMillisec = millisecondssince1970 + (1000 * 60);
var newDate = new Date(newMillisec);
console.log(newDate.getHours() + ":"
+ newDate.getMinutes() + ":"
+ newDate.getSeconds());
Please try this,
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
var date = new Date(Time);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
Here is working example https://jsfiddle.net/oa7j3krs/2/
$('#time').click(function(){
var d = new Date($.now()+60*1000); // current time + 60s
$(this).val(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
});
Anyway, I found a way to do this. Maybe it's not the best but it will do the job.
$('#time').click(function(){
var currentTime = new Date();
var addOneMinute = currentTime.getMinutes();
addOneMinute=parseInt(addOneMinute) + 1;
var Time=currentTime.getHours() + ":"
+ addOneMinute + ":"
+ currentTime.getSeconds();
console.log(Time);
$(this).val(Time);
});

How to keep updating datetime every minute in Javascript?

I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc

Categories