进度条百分比计算求助:基于余额与任务时间参数的占比计算
Got it, let's work through this step by step. From your parameters, I’m assuming you want a time-based progress bar (since you have creation and deadline timestamps)—the balance you mentioned is the total funds you invested in the task, but it doesn’t directly affect the time-driven progress calculation. Here’s how to compute it:
Core Logic Overview
The progress percentage will represent how much time has passed since the task was created, relative to the total time between creation and the deadline. We’ll handle edge cases to avoid invalid values like negative percentages or over 100%.
Step 1: Calculate the Total Task Duration
First, find the total length of the task in milliseconds by subtracting the creation timestamp from the deadline:
total_duration = task_deadline_ms - task_creation_ms
Quick note: If total_duration is 0 (meaning the task was created and set to end at the exact same time), you can default the progress to 100% since the task is already complete.
Step 2: Calculate Elapsed Time Since Task Creation
Next, get the current timestamp (in milliseconds) and compute how much time has passed since the task started:
// In JavaScript current_time_ms = Date.now(); // In Python import time current_time_ms = time.time() * 1000 elapsed_time_ms = current_time_ms - task_creation_ms
Step 3: Compute the Progress Percentage
Now calculate the percentage, with checks to keep it within 0-100%:
if elapsed_time_ms <= 0: # Task hasn't started yet progress_percent = 0.0 elif elapsed_time_ms >= total_duration: # Task has already ended progress_percent = 100.0 else: # Calculate the proportional progress progress_percent = (elapsed_time_ms / total_duration) * 100
You can round this to 1 or 2 decimal places for cleaner display, like round(progress_percent, 2).
Example Using Your Sample Values
Let’s plug in your numbers to see it in action:
- Task creation time: 1604919015906 ms
- Task deadline: 1612047600000 ms
- Total duration = 1612047600000 - 1604919015906 = 7128584094 ms (~82.5 days)
If the current time is 1608473315906 ms (roughly halfway between creation and deadline):
- Elapsed time = 1608473315906 - 1604919015906 = 3554300000 ms
- Progress percent = (3554300000 / 7128584094) * 100 ≈ 49.86%
What About the Balance?
If you actually wanted the progress bar to reflect something related to the balance (like funds used vs. total invested), you’d need an extra parameter (e.g., "amount of funds spent so far"). But based on the parameters you shared, time-based progress is the most logical fit. If that’s not what you need, feel free to clarify your goal!
内容的提问来源于stack exchange,提问作者user3880197

