手机版 收藏 导航

如何在网页上显示文章发布时间_如何在网页上显示当地时间和天气

原创   www.link114.cn   2024-01-04 12:42:59

如何在网页上显示文章发布时间_如何在网页上显示当地时间和天气

在网页上显示文章发布时间是一个常见的功能。可以使用 JavaScript 动态获取文章发布的时间并在页面上显示。可以使用 new Date() 方法获取当前时间,格式化为所需的时间格式。例如:


var publishDate = new Date('2023-04-20T12:00:00');
var options = { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' };
var formattedDate = publishDate.toLocaleDateString('en-US', options);
document.getElementById('publish-date').innerHTML = formattedDate;

这样就可以在页面上显示文章的发布时间。

除显示文章发布时间外,在网页上显示当地时间和天气信息也是一个常见的需求。可以使用 JavaScript 调用第三方天气 API 获取当前位置的天气信息,在页面上显示。例如:


navigator.geolocation.getCurrentPosition(function(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  var weatherApiUrl = 'https://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=YOUR_API_KEY&units=metric';
  fetch(weatherApiUrl)
    .then(response => response.json())
    .then(data => {
      var temperature = data.main.temp;
      var weatherDescription = data.weather[0].description;
      var currentTime = new Date().toLocaleString();
      document.getElementById('local-time').innerHTML = currentTime;
      document.getElementById('local-weather').innerHTML = temperature + '°C, ' + weatherDescription;
    });
});

这样就可以在页面上显示当地时间和天气信息。