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;
};
Related
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}`);
I am trying to convert time duration from the format of mm:ss.mss to entirely milliseconds and back.
I've already have a working function for converting from milliseconds to duration but I cannot seem to get it the other way around.
Lets say for instance that I have the duration 32:29.060, I want to convert it to milliseconds. For that I use this function:
function millisecondsToTime(ms, digits) {
digits = digits || 12;
return new Date(ms).toISOString().slice(23-digits, -1);
}
var a = millisecondsToTime(5549060, 9);
but whenever I try to convert back to time duration, I fail. I've tried parsing individually the minutes, seconds and milliseconds but it doesn't seem to work.
Here is the code that I've used for it:
var firstSplit = a.split(':')
var minutes = firstSplit[0]; //1
var secondSplit = firstSplit[1].split('.');
var seconds = secondSplit[0]; //2
var millisec = secondSplit[1]; //3
var conversion = ((+minutes) * 60 + (+seconds) * 60 + (+millisec))*1000;
I have an input bar which takes the format of mm:ss.mss and I need to convert it to milliseconds. How can I do that?
you can just return a
new Date(ms)
to get a date from ms.
And to get the same date as ms,
date.getTime() // returns ms from date object
Full example:
const ms = 5549060
const date = new Date(ms) // get a date from ms
console.log(date.getTime) // logs 5569060
If your input is a string in the format of mm:ss.mss, and you want to get a date from it, you can use moment.
const moment = require('moment')
const date = moment('22:15.143', 'mm:ss.SSS') // get date from pre specified format
You can use the string methods indexOf() and substr() to get the individual numbers out of your string and calculate the time accordingly.
I'm afraid though your millisecondsToTime() function isn't working properly.
5549060 milliseconds are roughly 92 minutes and it's returning 32:29.060
function backToTime(time) {
var index = time.indexOf(":");
var minutes = time.substr(0, index);
var seconds = time.substr(index + 1, time.indexOf(".") - (index + 1));
var milliseconds = time.substr(time.indexOf(".") + 1, time.length);
return parseInt(minutes * 60 * 1000) + parseInt(seconds * 1000) + parseInt(milliseconds);
}
console.log(backToTime("32:29.060"));
Your conversion to milliseconds is not working, this is basic math approach to both conversions:
let input = 5549060
//toDuration
let seconds = Math.floor(input / 1000);
let ms = input - seconds*1000;
let m = Math.floor(seconds / 60);
let s = seconds - m*60;
duration = m + ":" + s + "." + ms
console.log(duration)
//toMilliseconds
let holder = duration.split(":");
m = parseInt(holder[0]);
holder = holder[1].split(".");
s = parseInt(holder[0]);
ms = parseInt(holder[1]);
milliseconds = (m*60 + s)*1000 + ms
console.log(milliseconds)
If needed add check for ms length to add 0s, if you need it to have length of 3
I think your milliseconds to duration converter will be broken for durations above 60 minutes. This is because using Date the minutes field will wrap over into the minutes after 59 seconds have passed. If you want to get good support for values beyond 59 in your first field, I think maybe moving to a regex-based parser and using multiplication and addition, division and modulo to extract and reduce the fields manually might be nice. Something like this maybe:
var duration = ms => `${(ms / 60000) | 0}`.padStart(2, '0') + `:` + `${ms % 60000 / 1000 | 0}`.padStart(2, '0') + `.` + `${ms % 1000}`.padStart(3, '0')
var millisec = durat => (match => match && Number(match[1]) * 60000 + Number(match[2]) * 1000 + Number(match[3]))(/^([0-9]+)\:([0-5][0-9])\.([0-9]{3})$/.exec(durat))
You can see given the input 5549060, this function provides output 92:29.60, which is exactly 60 seconds greater than your own, and I believe to be correct. Maybe it's intentional for your usecase, but I can't imagine that being so desirable generally...
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);