写一个方法把分钟转化为时分,例如:150->02:30

function minutesToHoursMinutes(totalMinutes) {
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;

  // Pad with leading zeros if needed
  const formattedHours = String(hours).padStart(2, '0');
  const formattedMinutes = String(minutes).padStart(2, '0');

  return `${formattedHours}:${formattedMinutes}`;
}


// Examples:
console.log(minutesToHoursMinutes(150)); // Output: 02:30
console.log(minutesToHoursMinutes(5));   // Output: 00:05
console.log(minutesToHoursMinutes(60));   // Output: 01:00
console.log(minutesToHoursMinutes(75));  // Output: 01:15 
console.log(minutesToHoursMinutes(450)); // Output: 07:30

This function takes an integer representing the total number of minutes as input and returns a string in the format "HH:MM". Here's a breakdown:

  1. Calculate Hours and Minutes:

    • Math.floor(totalMinutes / 60) calculates the whole number of hours by dividing the total minutes by 60 and discarding the remainder.
    • totalMinutes % 60 calculates the remaining minutes using the modulo operator.
  2. Pad with Leading Zeros:

    • String(hours).padStart(2, '0') converts the hours to a string and then uses padStart(2, '0') to add a leading zero if the hours are a single digit (e.g., 0, 1, ..., 9).
    • The same logic is applied to the minutes.
  3. Return Formatted String:

    • The formatted hours and minutes are concatenated with a colon in between to create the final "HH:MM" string.

This approach is concise and efficient for frontend development in JavaScript. It ensures that the output is always in the correct format, even for single-digit hours and minutes.

posted @ 2024-12-04 09:22  王铁柱6  阅读(40)  评论(0)    收藏  举报