You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TravelTimeHoursDiff与TravelTimeMinutesDiff格式化为两位数时间

Solution for Two-Digit Time Formatting

Hey there! Let's get that time display looking clean with proper two-digit hours and minutes (like 07:00 instead of 7:0). Here's a simple, reusable way to fix this in your existing code:

Step 1: Create a Reusable Pad-Zero Function

First, make a small helper function that takes a number and returns it as a two-digit string. This will handle both hours and minutes seamlessly:

function padZero(num) {
  // If the number is less than 10, prepend a zero; otherwise return as-is
  return num < 10 ? `0${num}` : `${num}`;
}

Step 2: Integrate the Function into Your Existing Code

Now update your code to use this function when calculating and formatting TravelTimeHoursDiff and TravelTimeMinutesDiff. Here's the modified version with clear comments explaining the changes:

if ($scope.DispatchStatus.ArrivalTime != undefined){
  var today = $rootScope.getSysDate().split(" ");
  var timeArrival = new Date(today[0] + ' ' + $scope.DispatchStatus.ArrivalTime);
  var TravelTime = new Date(today[0] + ' ' + $scope.Route.TravelTime);
  
  var timeArrivalHours = timeArrival.getHours();
  var timeArrivalMinutes = timeArrival.getMinutes(); // Added to capture minute values
  var travelTimeHours = TravelTime.getHours();
  var travelTimeMinutes = TravelTime.getMinutes(); // Added to capture minute values
  
  // Calculate the hour and minute differences
  var TravelTimeHoursDiff = timeArrivalHours - travelTimeHours;
  var TravelTimeMinutesDiff = timeArrivalMinutes - travelTimeMinutes;
  
  // Format values to two digits using our helper function
  var formattedHours = padZero(TravelTimeHoursDiff);
  var formattedMinutes = padZero(TravelTimeMinutesDiff);
  
  // Combine into your desired time string (e.g., "07:00")
  var formattedTravelTime = `${formattedHours}:${formattedMinutes}`;
  
  // Use formattedTravelTime wherever you need to display this value
  console.log(formattedTravelTime); // Example output: "07:00"
}

Quick Notes:

  • The padZero function is reusable across your codebase for any two-digit formatting needs (not just time!).
  • I added code to capture minute values since your original snippet was cut off—make sure you're calculating minute differences correctly for full accuracy.
  • If your time difference could result in negative values (e.g., arrival time is earlier than travel time), you might want to add logic to handle that (like taking the absolute value or adjusting for overnight times) depending on your specific use case.

内容的提问来源于stack exchange,提问作者Malik Muhammad Bilal Awan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:54:32