获取当前时间

  • 获取当前时间
function getCurrentTime() {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0'); // 补零
  const minutes = now.getMinutes().toString().padStart(2, '0'); // 补零
  return `${hours}:${minutes}`;
}
  • 如果想要只返回10的倍数的分钟数呢?比如:09:10 / 09:20 / 09:30
function getCurrentTime() {
  const now = new Date();
  let hours = now.getHours();
  let minutes = now.getMinutes();
  
  // Calculate the rounded up minutes
  minutes = Math.ceil(minutes / 10) * 10;
  
  // Handle overflow when minutes reach 60
  if (minutes >= 60) {
    minutes = 0;
    hours++;
    // Handle overflow when hours reach 24
    if (hours >= 24) {
      hours = 0;
    }
  }
  
  // Format with leading zeros
  const formattedHours = hours.toString().padStart(2, '0');
  const formattedMinutes = minutes.toString().padStart(2, '0');
  
  return `${formattedHours}:${formattedMinutes}`;
}

你可能感兴趣的:(前端,javascript,开发语言)