This question already has answers here:
getMinutes() 0-9 - How to display two digit numbers?
(21 answers)
Closed 3 years ago.
I would like to get it to display 0 infront of the output if it's under 10.
const time = new Date();
let hour = today.getHours();
let minute = today.getMinutes();
let second = today.getSeconds();
if (second < 10) {
second = 0 + second;
}
console.log(`Time is ${hour} : ${minute} : ${second}`);
Instead of showing for example 19:5:7, I would like to see 19:05:07
///
Ok, I found out what the problem was. 0 was a number not a string. Just started with JS.
Thanks for the help!
You could pad the value with leading zeroes.
const pad2 = s => s.toString().padStart(2, '0');
let today = new Date;
let hour = pad2(today.getHours());
let minute = pad2(today.getMinutes());
let second = pad2(today.getSeconds());
console.log(`Time is ${hour}:${minute}:${second}`);
Related
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Adding "0" if clock have one digit
(9 answers)
Closed 1 year ago.
I am having trouble understanding how the below mentioned function work.
const getTime = (time) =>{
return(
Math.floor(time/60) + ":" + ("0" + Math.floor(time%60)).slice(-2)
);
};
mainly the ("0" + Math.floor(time%60)).slice(-2) part. can somebody explain this in a simple way ?
As far as I understand it, the time in the brackets tells you to enter a time. For example;
const d = new Date();
const t = d.getMinutes();
console.log(t);
The main part you ask is adding the remainder of the 60th of the time you entered to 0. When we write the same code this way, if my minute is 33, we will see 34 output;
const d = new Date();
const t = d.getMinutes();
const getTime = "0" + Math.floor(t%60);
getTime.slice(-2);
console.log(t);
**Edit: An alternative**
You're looking at the `remainder operator` and the `slice method`.
Whenever code is confusing, it can help to break it up into named pieces and print them. This snippet does just that:
// Tests
formattedMinsAndSecs(5);
formattedMinsAndSecs(3611);
formattedMinsAndSecs(999999);
// Reworked function
function formattedMinsAndSecs(seconds){
console.log("input:", seconds);
const minsPart = Math.floor(seconds / 60);
console.log("minsPart:", minsPart);
// Remainder operator (%) gets remainder after division
const secsPart = Math.floor(seconds % 60);
console.log("secsPart:", secsPart);
const withLeadingZero = "0" + secsPart;
console.log("withLeadingZero:", withLeadingZero);
// slice method with 1 negative argument gets last N chars
const lastTwoCharacters = withLeadingZero.slice(-2);
console.log("lastTwoCharacters:", lastTwoCharacters);
const formatted = minsPart + ":" + lastTwoCharacters
console.log("formatted:", formatted, "\n\n");
return formatted;
};
This question already has answers here:
Check time difference in Javascript
(19 answers)
Closed 2 years ago.
i.e. I want to calculate the time difference from 8.30pm to 9pm in 24hr format.
so far i have:
let start = 2030;
let end = 2100;
let timeDiff = end - start;
But this gives me 70 as an answer.
How do I get 30 minutes as an answer?
You need to specify the correct format of your time. you can calculate like below.
let start = new Date('1900/01/01 08:30 PM');
let end = new Date('1900/01/01 09:00 PM');
let minDiff = (Math.abs(start - end) / 1000)/60;
let hourDiff = ((Math.abs(start - end) / 1000)/60)/60;
let dayDiff = parseInt((((Math.abs(start - end) / 1000)/60)/60)/24);
This question already has answers here:
How can I convert a HH:mm:ss string to a JavaScript Date object?
(3 answers)
Closed 4 years ago.
I am having a field called Duration it contains time like 00:20:40.How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds .I tried the following but didn't work.
var time = new Date('00:10:40');
time.getMinutes();
Output will look like:
The given time is <20 minute.Hence i need to check like this
if(<20 minutes){...}
You have to create Date Object with Date to use it.
var d = new Date("1970-01-01 20:18:02");
document.write(d.getMinutes());
You can do the following:
var time = "00:20:40".split(":");
var minutes = time[1];
The given string "00:20:40" is not a valid date string and cannot be passed to new Date() as an argument. In this case, you can use the above solution which will split the string and give you an array consisting of [hh, mm, ss] and you will be able to get the minutes at time[1].
I hope it helps.
function toSeconds (duration) {
const regex = /(\d+):(\d+):(\d+)/;
const matched = duration.match(regex);
const hours = parseInt(matched[1]);
const minutes = parseInt(matched[2]);
const seconds = parseInt(matched[3]);
return (hours * 60 * 60) + (minutes * 60) + seconds;
}
function toMinutes (duration) {
const seconds = toSeconds(duration);
return seconds / 60;
}
function toHours (duration) {
const minutes = toMinutes(duration);
return minutes / 60;
}
toSeconds('00:20:40') // 1240
toMinutes('00:20:40') // 20.666666666666668
toMinutes('01:20:40') // 80.66666666666667
toHours('01:20:40') // 1.3444444444444446
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
How can I compare two time strings in the format HH:MM:SS?
(16 answers)
Closed 4 years ago.
How to find the difference between to times in JavaScript?
Here is the pseudocode I've come up with
var firstTime = "20:24:00";
var secondTime = "20:00:52";
console.log(firstTime - secondTime);// 23:08 (23 minutes, 8 seconds)
You could use new Date().setHours() to make to dates from the time you have and then subtract them, make a new date from the difference:
var firstTime = "20:24:00";
var secondTime = "20:00:52";
// transform variables into parameters
let dateA = new Date().setHours(...(firstTime.split(":")));
let dateB = new Date().setHours(...(secondTime.split(":")));
let diff = new Date(dateA-dateB);
console.log(`Differnce: ${diff.getUTCHours()}:${diff.getUTCMinutes()}:${diff.getUTCSeconds()}`);
Try this:
var myDate1 = new Date();
myDate1.setHours(20, 24, 00, 0);
var myDate2 = new Date();
myDate2.setHours(20, 00, 52, 0);
If you subtract them directly, it will give you a timestamp value. You can convert this value by saying:
var result = myDate1 - myDate2; // returns timestamp
var hours = new Date(result).getHours(); // returns hours
A while ago I had made a function similar to the one described:
let timeOp = function(operation, initial, value) {
// define the type of operation in bool if needed
if(typeof operation == "string") {
var operation = (operation == 'add') ? true : false;
}
// convert to minutes `value` if needded
if(!Number.isInteger(value)) {
var time = value.split(':');
value = parseInt(time[0]) * 60 + parseInt(time[1]);
}
// split the string and get the time in minutes
var time = initial.split(':');
time = parseInt(time[0]) * 60 + parseInt(time[1]);
// add or substract `value` to minute
time += (operation) ? value : -value;
// standardise minutes into hours
var hour = Math.floor(time / 60);
var minute = time % 60;
// return with '0' before if needed
return hour + ':' + ((minute>=10) ? minute : ('0' + minute))
}
let firstTime = "20:24";
let secondTime = "20:00";
console.log(timeOp('substract', firstTime, secondTime)
It's not perfect and it doesn't allow to use seconds. But you can figure that out pretty easily by modifying the above code.
This question already has answers here:
Leading zeros in minutes
(6 answers)
Closed 8 years ago.
I have a clock made that displays the current time in Hours:Minutes:Seconds. Currently the time is displayed as so 20:30:25, but my problem is that when the time is a single digit for example 1.05 (3 seconds) am, it will appear like this on the clock 1:5:3. I want it to appear like this 01:05:03.
How can this be done?
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
today = hours+':'+minutes+':'+seconds;
document.write(today);
A simple way is to use a slice(-2) trick to always let the number with a preceding zero (if needed)
Slice, with a negative parameter, takes the last n characters of a string, in this case, always a two digit value:
var today = new Date();
var hours = ("00" + today.getHours()).slice(-2);
var minutes = ("00" + today.getMinutes()).slice(-2);
var seconds = ("00" + today.getSeconds()).slice(-2);
alert(hours+":"+minutes+":"+seconds);
Simply add zeros! I used ternary operator to do it.
var today = new Date();
var hours = today.getHours() <10 ? "0"+today.getHours(): today.getHours();
var minutes = today.getMinutes() <10 ? "0"+today.getMinutes(): today.getMinutes();
var seconds = today.getSeconds() <10 ? "0"+today.getSeconds(): today.getSeconds();
today = hours+':'+minutes+':'+seconds;
document.write(today);