如何将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
padZerofunction 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
相关产品推荐
相关产品推荐

