This question already has answers here:
Convert HH:MM:SS string to seconds only in javascript
(14 answers)
Closed 3 years ago.
I have a time format which is for example 1:50:60 (Hours:Minutes:Seconds) or also could be 00:50:60 (Minutes:Seconds) - depends. Now i want to convert that value hours, minutes, seconds to Seconds.
So 1:50:60 would be 6660 seconds.
Try the below code
var hms = '09:05:03';
var s = hms.split(':');
var seconds = (+s[0]) * 60 * 60 + (+s[1]) * 60 + (+s[2]);
console.log(seconds);
var hm = '00:55:03';
var s = hm.split(':');
var seconds = (+s[0]) * 60 * 60 + (+s[1]) * 60 + (+s[2]);
console.log(seconds);
Try this:
var hms = '01:50:60'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);
Related
I am trying to code a count down timer in Vanilla Javascript. Below is the code:-
var futureDate = new Date("oct 31,2021 10:00:00").getTime();
var currentDate = new Date().getTime();
var diffTime = futureDate - currentDate;
console.log(diffTime);
var days = Math.floor(diffTime / (1000* 24* 60*60));
console.log(days);
var hours = Math.floor(diffTime / (1000 * 60 * 60));
console.log(hours);
var minutes = Math.floor(diffTime / (1000 * 60));
console.log(minutes);
var seconds = Math.floor(diffTime / (1000));
console.log(seconds);
Below is the output of the code provided in the console.
This output is in accordance with below image
But I am failing to understand the particular code written in w3schools as highlighted in blue color in the image below
I am not able to figure out the difference between 2 code written?
Date.getTime() returns the number of milliseconds since the Unix epoch (1900-01-01 00:00:00).
When you subtract the time between 2 dates, you will get the time difference in milliseconds. In your code, you are showing
The total number of hours between the dates
The total number of minutes between the dates
The total number of seconds between the dates
Let's take the number of hours as an example, the code written in w3schools takes the remainder from dividing the time difference by the number of milliseconds per day. This way, you will get the time difference in less than 24 hours and you can use it to calculate the time difference in hours.
Do the same for the minutes and seconds and you will get the same result written in w3schools
var futureDate = new Date( "oct 31,2021 10:00:00" ).getTime();
var currentDate = new Date().getTime();
var timeDiffInMilliseconds = futureDate - currentDate;
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60; // 1000 * 60
var millisecondsPerHour = millisecondsPerMinute * 60; // 1000 * 60 * 60
var millisecondsPerDay = millisecondsPerHour * 24; // 1000 * 60 * 60 * 24
console.log( 'timeDiffInMilliseconds: ' + timeDiffInMilliseconds );
var days = Math.floor( timeDiffInMilliseconds / millisecondsPerDay );
console.log( 'days: ' + days );
var timeDiffInLessThan1Day = timeDiffInMilliseconds % millisecondsPerDay;
var hours = Math.floor( timeDiffInLessThan1Day / millisecondsPerHour );
console.log( 'hours: ' + hours );
var timeDiffInLessThan1Hour = timeDiffInMilliseconds % millisecondsPerHour;
var minutes = Math.floor( timeDiffInLessThan1Hour / millisecondsPerMinute );
console.log( 'minutes: ' + minutes );
var timeDiffInLessThan1Minute = timeDiffInMilliseconds % millisecondsPerMinute;
var seconds = Math.floor( timeDiffInLessThan1Minute / millisecondsPerSecond );
console.log( 'seconds: ' + seconds );
Okay, first you need to understand the basic concept of dates in vanilla javascript.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
1 day = 24 hours
Math.floor is simply used for returning the highest rounded value possible.
Now coming to your question,
var distance = countDownDate - now;
This line basically takes two UNIX format date integers and gives you the difference in the form of unix timestamp. So once you get the difference you need to find out how many hours, minutes and days it comprises of, and that's just it.
We use the simple formulas I mentioned to top to identify just that.
1000 * 60 * 60 * 24 is 1 day
So we divide the total difference in two dates by the 1 day to get the number of days in total with the following line:
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
Similarly, with the code below, we take the difference in two dates and first get the number of days from it and then whatever time remains we use that time to further calculate the hours by dividing the value by (1000 * 60 * 60).
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
The following line first calculates the number of hours from the difference and then whatever remains is then further divided by a minute to get the totals minutes remaining. Similarly, concept will be applied to calculate the seconds.
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
I am sending the data from my database as 24 hr format, but when i use it on front-end for time counter as below the output gives 'none'.
Also,When I print the 'plan_deactive_date' it shows time in 12 hr format.
So, is there any way to convert the datetime from 12 hr format to 24 hr format?
<script>
// Set the date we're counting down to
var countDownDate = new Date("{{plan_deactive_date}}").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Expired";
}
}, 1000);
</script>
You can use
date.toLocaleDateString('en-GB')
Read this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You can use
To get date in 24 hour format
data.toLocaleString('en-GB')
To get date in 12 hour format
data.toLocaleString('en')
I am working on an Auction site in Asp.net MVC and I am trying to be able to display how a timer of how much time is left on each item's auction. I pass a list of items to my cshtml page with my Model and then iterate through them like so:
My javascript function to start timer:
function countdown(time) {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = time - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="timeLeft"
document.getElementById("timeLeft").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
}, 1000);
Then my iterator of my Model, calling js function with the item's end date
#foreach (var item in Model)
{
//code here
countdown(#item.EndDate)
<text id="timeLeft"></text>
}
I have my script referenced by <script src="~/Scripts/countdown.js" />
The problem I am having is how to call this js function with a c# razor variable. Doing something basic for one item like:
<body onload= "countdown('#item.EndDate')">
When I put my razor variable it greys out my function.
How do I need to go about passing my variable into my js function?
EX: (with singular Model item)
Try with this syntax:
#foreach (var item in Model)
{
//code here
countdown(`${#item.EndDate}`)
}
If you want to make a timer in javascript, I would use window.setInterval function, then set the second parameter to be time interval.
This function countdown need to pass three parameter
End Year
End Month
End Day
function countdown(endYear,endMonth,endDay) {
window.setInterval(function () { StartCount(endYear, endMonth, endDay, 'andy timer'); }, 1000);
}
function StartCount(endYear,endMonth,endDay){
var now=new Date();
var endDate=new Date(endYear,endMonth-1,endDay);
var leftTime=endDate.getTime() - now.getTime();
var leftSecond=parseInt(leftTime/1000);
var day=Math.floor(leftSecond/(60*60*24));
var hour=Math.floor((leftSecond-day*24*60*60)/3600);
var minute=Math.floor((leftSecond - day * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftSecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
document.getElementById("timeLeft").innerHTML = day + "d " + hour + "h "
+ minute + "m " + second + "s ";
}
countdown(2018,10,5)
<div id='timeLeft'></div>
You can use this on the body tag
<body onload= "countdown(#Model.EndDate.Year,#Model.EndDate.Month,#Model.EndDate.Day)">
EDIT
It worked on c# MVC online: https://dotnetfiddle.net/ERcwAb
I figured out a crazy way to do what I was trying to do, might not be efficient, might be a sin to the entire coding community, but here it is:
#foreach (var item in Model)
{
<script>
function countdown(endYear, endMonth, endDay, endHours, endMin, num) {
window.setInterval(function () { StartCount(endYear, endMonth, endDay, endHours, endMin, num); }, 1000);
}
function StartCount(endYear, endMonth, endDay, endHours, endMin, num) {
var now = new Date();
var endDate = new Date(endYear, endMonth - 1, endDay, endHours, endMin);
var leftTime = endDate.getTime() - now.getTime();
var leftSecond = parseInt(leftTime / 1000);
var day = Math.floor(leftSecond / (60 * 60 * 24));
var hour = Math.floor((leftSecond - day * 24 * 60 * 60) / 3600);
var minute = Math.floor((leftSecond - day * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftSecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
var id = "timeLeft" + num;
document.getElementById(id).innerHTML = day + "d " + hour + "h "
+ minute + "m " + second + "s ";
}
countdown(#item.EndDate.Year, #item.EndDate.Month, #item.EndDate.Day,#item.EndDate.Hour, #item.EndDate.Minute, #num)
</script>
#{string countNum = "timeLeft" + num;}
<text id= #countNum></text>
#{num++;}
//code
}
But it still loads asynchronously where the items will all load, then the clocks all appear a second later and all content is moved accordingly. May be due to my initial issue of not doing able to call body onload.
This question already has answers here:
How to add days to Date?
(56 answers)
Closed 6 years ago.
This is how I get todays timestamp:
var timestampNow = Math.floor(Date.now() / 1000);
I want to set timestampNow to 4 weeks from now.
My initial guess is to use Math.floor(Date.now(28) / 1000);?
I believe this would work:
let fourWeeksFromNow = new Date();
fourWeeksFromNow.setDate(fourWeeksFromNow.getDate() + 28)
javascript isn't that great when it comes to dates, so you need to parse the date to a timestamp and modify the milliseconds. but the maths is not very hard.
var timestamp4weeks = Date.now() + (1000 * 60 * 60 * 24 * 7 * 4)
milliseconds => seconds === * 1000
seconds => minutes === * 60
minutes => hours === * 60
hours => days === * 24
days => weeks === * 7
Moment.js makes this easy. The following are equivalent:
var days = moment().add(28, 'days');
var weeks = moment().add(4, 'weeks');
This question already has answers here:
Convert seconds to HH-MM-SS with JavaScript?
(38 answers)
Closed 6 years ago.
Suppose I have an integer number as a variable. (this number can be any integer number).
Now I want to create a countdown timer based on this number on the page.
To create countDown, I am using jquery-countdownTimer plugin.
A simple usage of this plugin is like this :
$(function(){
$("#hms_timer").countdowntimer({
hours : 3‚
minutes : 10‚
seconds : 10‚
size : "lg"‚
pauseButton : "pauseBtnhms"‚
stopButton : "stopBtnhms"
});
});
As you see , it gets hours , minutes and seconds in 3 separate numbers.
Now my question is how can I convert an integer number to Equivalent hours , minutes and seconds in simplest way?
function getTime(s) {
var secs = parseInt(s, 10); // don't forget the second param
var hours = Math.floor(secs / 3600);
var minutes = Math.floor((secs - (hours * 3600)) / 60);
var seconds = secs - (hours * 3600) - (minutes * 60);
return {
hours: hours,
minutes: minutes,
seconds: seconds
};
}
var time = getTime("3792");
alert("Hours: " + time.hours + "\nMinutes: " + time.minutes + "\nSeconds: " + time.seconds);