-1

我正在为搜索的城市中的当前天气创建实时应用程序。但是,我目前正在努力显示当前时间的时间,我想知道如何修复它以首先将其显示为 17:06 而不是当前的 17:6,以及如果想要如何将其显示为下午 5:06 而不是军事风格。谢谢!

function formatDate(theDate) {
  let now = new Date();

  let currentDate = document.querySelector("#currentDate");

  console.log(now.getDate());

  console.log(now.getMilliseconds());

  console.log(now.getDay());
  console.log(now.getFullYear());
  console.log(now.getMonth());

  let date = now.getDate();
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let year = now.getFullYear();
  let days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  let months = [
    "Jan",
    "Feb",
    "March",
    "April",
    "May",
    "June",
    "July",
    "Aug",
    "Sept",
    "Oct",
    "Nov",
    "Dec",
  ];
  let day = days[now.getDay()];
  let month = months[now.getMonth()];

  currentDate.innerHTML = ` ${day} ${hours}:${minutes}`;
  return theDate;
}

window.onload = formatDate();

function currentCity() {
  event.preventDefault();
  let city = document.querySelector("#city");
  city.innerHTML = "Works";
}
function searchCity() {
  event.preventDefault();
  let serachInput = document.querySelector("#search-input");
}
let runSearch = document.querySelector("#search-button");

runSearch.addEventListener("click", currentCity);

4

2 回答 2

1

You can use the padStart method to add leading zeros to strings. Remember to cast your number to a string before using padStart: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

For the hours and meridian, it's just a bit of arithmetics.

const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();

const formattedHours = (hours % 12).toString().padStart(2, '0');
const formattedMinutes = minutes.toString().padStart(2, '0')
const meridian = hours / 12 < 1 ? 'AM' : 'PM'

const time = `${formattedHours}:${formattedMinutes}${meridian}`;

console.log(time)

于 2021-01-16T22:40:06.433 回答
0

使用内置的 JavaScript 方法获取日期时间字符串

var currentDate = new Date();
currentDate.toDateString(); //"Sat Jan 16 2021"
currentDate.toGMTString(); //"Sat, 16 Jan 2021 22:22:51 GMT"
currentDate.toISOString(); //"2021-01-16T22:22:51.698Z"
currentDate.toJSON(); //Returns the same as above
currentDate.toLocaleDateString(); //"1/16/2021"
currentDate.toLocaleTimeString(); //"2:22:51 PM"

在这里查看所有“to”方法https://www.w3schools.com/jsref/jsref_obj_date.asp

于 2021-01-16T22:27:35.310 回答