简体   繁体   中英

How to increase or decrease in percentage a time in hh:mm:ss format in javascript

I have a problem with javascript. I'm pretty new, so I appreciate your help in advance.

I have a form in which I have a date in hh: mm: ss format and to which through an input field I would like to increase or decrease the hh: mm: ss by percentage. The percentage can be integer or decimal number.

That is, in one hour "example". 17:22:14 I would like to increase by 6% or if it is 14.3% decimal, or else the same value but in negative, ie decrease by 6% or 14.3%.

I have an example to show the percentage of an increase from a given hour but I can't do what I want to do.


With this example in PHP I would know the percentage from a date, but I don't want this, I want to know how to increase or decrease in percentage from a given time and in javascript.

<?php

$date = '08:53:34';
$parts = explode(':', $date);
$secs = $parts[0] * 3600 + $parts[1] * 60 + $parts[2];

// day has 86 400 seconds
echo $secs / 864 . '%'; // return 37.05% (you can round it)

?>

And in javascript I have this example, but the other way around. What I want is to increase or decrease not knowing the increased time from a given hour.

var time_begin = '08:00:00';       
var a = time_begin.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var start_time = Math.round((seconds/(24*60*60))*100);   

Thanks in advance

You can use for solve your problem standart JS object Date(); Algorithm is easy:

1) Make Date object of current or needed date. (today variable in my code)

2) Make Date of ending date, percentage to this date we'll looking

3) Just looking for difference between today date and tomorrow

4) Now we received percent that remained until tomorrow(Or other date).

5) If your need passed percents just use 100 - ((tomorrow - today) / ONE_DAY * 100) in last varibale, before use result

6) For increasing/decreasing use example.

Example is here:

const ONE_DAY = 8.64e7; // 86400000 milliseconds
let time = "08:54:33"; // Your time where your looking %
let today = new Date(); 
today.setHours(time.split(":")[0], time.split(":")[1], time.split(":")[2]); // Set time from what we will looking %

let tomorrow = new Date(Date.now() + ONE_DAY).setHours("0", "0", "0");
let percent = ((tomorrow - today) / ONE_DAY * 100).toFixed("2") + "%";

// it's for increase/decrease
const HOUR = 3.6e6; // 360000
const MINUTE = 6e4; // 60000
const SECOND = 1e3; // 1000
let incPercent = 0.03; // it's mean 3%
let increased = new Date(today.getTime() + (incPercent * HOUR));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM