On my project requires this kind of text response on a day and hours.
"2hrs"-- data as milliseconds, If i get 1h 30mins, It should be rounded-up to 2hrs.
i tried so many times but cannot catch the value. now am getting 1 hrs for below function.
can anyone help me to do this ? here is the function which i am using
const milliSec = 85600000;
const hrs = moment(moment.duration(milliSec)._data).format('HH[hrs]');
There are a couple of ways to solve your problem
Simple logic
let milliseconds = 85600000;
let hours = Math.floor(milliseconds/(1000*3600))
let minutes = Math.floor(milliseconds/(1000*60)) - hours * 60
if(minutes > 29){
console.log(hours + 1);
}
console.log(hours)
Using Moment.js
let milliseconds = 85600000
let hours = Math.floor(moment.duration(milliseconds).asHours())
let mins = Math.floor(moment.duration(milliseconds).asMinutes()) - hours * 60;
if(minutes > 29){
console.log(hours + 1);
}
console.log(hours)
Hope this helps you. Feel free for doubts.
Related
I have a problem, where I try to find the number of hours and minutes after I had last collected the item. For example, if I had collected the item 1 minute ago, the code should be able to print out the remaining time left to collect the item again(23 h and 59 m) in this format. Till now, I have worked out this much:
UserJSON is a JSON file with the user's name and the time of their last claim
let deltaHour = Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (60 * 60 * 24)
let deltaRealHour = Math.floor(deltaHour)
let deltaMin = ((deltaHour % 1) / 100) * 60
Please help me out.
Here is a possible solution.
You can use the function I wrote before (timeUntilNextClaim()), supply it with the last time that your user claimed the item (in epoch seconds) and it will return to you the delta milliseconds until the item can be claimed.
You can then use the second funciton I wrote for you (toHrsAndMinutes) to turn milliseconds into hours and minutes (rounded down of course).
Please let me know if you have any questions or would like any more help with this. I'd be happy to help.
function timeUntilNextClaim(LastClaim) {
/* this function takes an epoch time of the
last time the user claimed the item as an argument and
returns (in ms) the time until they can pick up the
item again */
let now = new Date();
// add 24 hours to last claim time to calculate next claim time
let timeTilClaim = (LastClaim + 8.64e7) - now;
if (timeTilClaim <= 0) {
return 0;
} else {
return timeTilClaim;
}
}
function toHrsAndMinutes(duration) {
// this function will return an array of [hours, minutes] of a duration specified in ms
var hours, minutes;
hours = Math.floor(duration / 3.6e6);
minutes = Math.floor((duration % 3.6e6) / 60000);
return [hours, minutes];
}
function test() {
// tests / Example Usage
let usrLastClaimTime = new Date() - 20160000; // lets pretend they claimed it last 5.6 hours ago
let now = new Date();
let msTilNextClaim = timeUntilNextClaim(usrLastClaimTime);
let hoursTilClaim, minsTilClaim;
[hoursTilClaim, minsTilClaim] = toHrsAndMinutes(msTilNextClaim);
console.log(`The current time is ${now}`);
console.log(`The item was last claimed at ${Date(usrLastClaimTime)}`);
console.log(`You can claim again in ${hoursTilClaim} Hours and ${minsTilClaim} Minutes`);
}
test();
getTime() is milliseconds since Jan 1, 1970, 00:00:00.000 GMT
let lastclaim = 1632196398605;
let delta = (new Date() - new Date(lastclaim)) / (60 * 1000 * 60);
let deltaHrs = Math.floor(delta);
let deltaMins = Math.floor((delta % 1) * 60);
console.log(`deltaHrs:`, deltaHrs);
console.log(`deltaMins:`, deltaMins);
Okay, so I am trying to calculate the time since 9:30 in the morning in Google Apps Script, and I want the output to look like this: XX hrs XX mins. the problem is when I try calculating the minutes since 9:30, of course, it gives me all the minutes, not just the leftover minutes after I've calculated the hours. I need the minutes to be a decimal so I can times it by 60 and display the output in a cell. This is the code I'm currently using:
function CALCTIME() {
const minutes = 1000 * 60;
const hours = minutes * 60;
const days = hours * 24;
const years = days * 365;
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
9,30,0),
diff = now.getTime() - then.getTime();
let hrs = diff / hours;
let mins = Math.floor((diff / minutes) % 60);
return Math.floor(hrs) + " hrs " + mins + " mins";
}
The issue is not the hrs, I have that all good. The minutes are the problem because I can't figure out how to replace just an index from a string. I've looked and tried the methods shown on these web pages and Stack Exchange links for answers and I couldn't find any:
https://www.w3schools.com/jsref/jsref_replace.asp
How do I replace a character at a particular index in JavaScript?
Questions: What do you expect these statements to do and why? mins.replaceAt(0, "0."); mins % 60; The first statement I expected to replace the first character in mins with "0." but then, #jabaa pointed out that I couldn't replace a number for a string, which I totally forgot and didn't take into account. The second statement I just forgot to put mins = mins % 60; which probably wouldn't have solved my problem anyway, I just forgot to put that there.
I've answered your questions, but someone has already answered my questions.
The reason it is not working is because you have:
diff = now.getTime() - then.getTime();
That line is going to get the time difference from now and 9:30am.
var hrs = diff / hours;
var mins = diff / minutes;
The two lines above are getting their own things. The first is how many hours and the second is how many minutes. So inherently you will be getting all the minutes and not the leftovers. There are multiple ways to fix it. Below is one way where the hours are right, so we take out every full hour from the minute's section.
Could look something like this:
let hrs = diff / hours;
let mins = (diff / minutes) % 60;
ALSO: The following line of code you have does nothing because you're not giving it anywhere to be stored in.
mins % 60
To fix you can do something like:
let testvar = mins % 60;
can someone help me out to write a function in react native to convert 234mins to 3hrs:54mins, and when it is less than 1hr, it shows just 59mins instead of 0hrs:59mins. Kindly indicate if I should give an example code.
Here it is:
const convertMinsToTime = (mins) => {
let hours = Math.floor(mins / 60);
let minutes = mins % 60;
minutes = minutes < 10 ? '0' + minutes : minutes;
return `${hours}hrs:${minutes}mins`;
}
Write the JavaScript to read the number of hours worked from the user. Then write the JavaScript to calculate how much money the user made if they were paid $12/hour for the first 40 hours worked, and $18/hr for all hours worked over 40. Then use console.log to print out the hours entered and the total amount made.
So that's the code I have to write.
I can get the first part no problem from 0-40. But I can't figure out how to have and if/else statement calculate the first 40 at $12/h and the remaining at $18/h.
my code right now looks like
let hours = Number(prompt("Numbers of hours worked"))
console.log("# of hours worked is " +hours)
let regularHours = (hours >=40
if (hours <= 40) {
console.log("In " +hours+ " you made $" +hours *12)
} else {
console.log("In " +hours+ "you made $" +)
can I define a variable to be like
let regularHours = hours <=40 *12
let overtimeHours = hours >40 *18
I tried that but it doesn't quite work.
Am I over complicating this?
Simply work out how many overtime hours they have worked, and then subtract it from your basic rate hours:
let hours = prompt('Enter your hours:'),
overtimeHours = Math.max(0, (hours - 40)),
baseRateHours = hours - overtimeHours;
let earnings = (baseRateHours * 12) + (overtimeHours * 18);
console.log(earnings);
Notice that we use Math.max() to prevent negative overtime hours from reducing the number of hours worked at the base rate.
let hours = prompt('Enter your hours');
let baseRateHours=40;
if(hours >baseRateHours){
let overTime= hours - baseRateHours;
let earnings= (baseRateHours*12) + (overTime*18);
}
else {
let earnings = hours*12;
}
console.log(earnings)
I have seen many posts about decimal hours to hours:minutes, but I have not found any that work for more than a days worth.
I am using the following with moment.js..
function formatHours(decimalHours) {
var duration = moment.duration(decimalHours, 'hours');
var hours = duration.hours();
var minutes = duration.minutes();
var date = moment().hours(hours).minutes(minutes);
var result = date.format('HH:mm');
return result;
}
but this does not work for greater than 24 hours,eg I have a hours coming in representing over a year.
Is there a ways to handle this, and also format for the current locale (as moment should do)
Thanks in advance for any help
I have no idea what Moment.js is and I am not sure what you are trying to achieve exactly. However, if I understand it well, you want to be able to convert decimal hours, going as high as you want, into a date.
I can propose you this code:
function formatHours(decimalHours) {
let minutes = decimalHours % 1;
let hours = decimalHours - minutes;
minutes *= 60;
minutes = Math.round(minutes);
if (hours > 24) {
var day = Math.floor(hours / 24);
hours %= 24;
}
let date = new Date();
date.setHours(hours);
date.setMinutes(minutes);
if (day) {
date.setDate(day);
}
console.log(`${date}`);
}
formatHours(24.88);
This will handle any decimal input up to 672.00 (28*24), you can just improve it to handle month and so on.
As commenter asked, what format are you looking for?
I would recommend adding moment-duration-format plugin which seems to be written just for your usecase. Then you could simply write:
function formatHours (decimalHours) {
return moment.duration.format(hoursDecimal, 'hours').format('D:HH:mm');
};
// This is for moment.js in angular
list : any = ["9:12","4:35","9:11"]; // declare properly
for(var i=0 ; i < 3; i++){
var parts = this.list[i].split(":");;
var hours = parseInt(parts[0]) ;
var minutes = parseInt(parts[1]);
this.a = moment.duration(this.a._data.hours,'hours').add(hours,'hours').add(this.a._data.minutes,'minutes').add(minutes,'minutes');
}
var totalHours = (24 * this.a._data.days) + this.a._data.hours ;
var total = totalHours + ":" +this.a._data.minutes;
}