此 JavaScript 代码在 Safari 浏览器中不起作用,但在其他浏览器中运行良好。 代码从时间戳值返回时间或日期,但在 safari 浏览器中不起作用。在 safari 代码中返回:aN.aN.aN 或 aN:aN 相关问题
// Get all elements with class "time" and "date"
const timeElements = document.getElementsByClassName("time");
const dateElements = document.getElementsByClassName("date");
// Function to format and display the time from a UNIX timestamp
function formatTimeElement(element) {
// Extract UNIX timestamp from the element's innerHTML
let unixTimeStamp = element.innerHTML;
// Convert UNIX timestamp to a JavaScript Date object
let dateObject = new Date(unixTimeStamp * 1000);
// Extract hours and minutes, ensuring leading zeros if needed
let hours = "0" + dateObject.getHours();
let minutes = "0" + dateObject.getMinutes();
// Create formatted time string (HH:MM)
let timeElement = hours.substr(-2) + ":" + minutes.substr(-2);
// Update the element's content with the formatted time
element.innerHTML = timeElement;
}
// Function to format and display the date from a UNIX timestamp
function formatDateElement(element) {
// Extract UNIX timestamp from the element's innerHTML
let unixTimeStamp = element.innerHTML;
// Convert UNIX timestamp to a JavaScript Date object
let dateObject = new Date(unixTimeStamp * 1000);
// Extract day, month, and year, ensuring leading zeros if needed
let day = "0" + dateObject.getDate();
let month = "0" + (dateObject.getMonth() + 1);
let year = dateObject.getFullYear().toString();
// Create formatted date string (DD.MM.YY)
let dateElement =
day.substr(-2) + "." + month.substr(-2) + "." + year.slice(-2);
// Update the element's content with the formatted date
element.innerHTML = dateElement;
}
// Loop through each element with class "time" and format the time
for (element of timeElements) {
formatTimeElement(element);
}
// Loop through each element with class "date" and format the date
for (element of dateElements) {
formatDateElement(element);
}
String.substr() 已弃用,因此您不能依赖浏览器来支持它。 String.slice() 支持负索引,因此可以使用
someString.slice(-2)
获取字符串的最后 2 个字符。
所以我们可以这样做并获得所需的输出,如下所示:
// Extract day, month, and year
// ensuring leading zeros if needed using String.padStart(minLength, paddingString)
let day = dateObject.getDate().toString().padStart(2, "0");
let month = (dateObject.getMonth() + 1).toString().padStart(2, "0");
let year = dateObject.getFullYear().toString().slice(-2);
// Create formatted date string (DD.MM.YY)
let dateElement =
day + "." + month + "." + year;
但是您可能会考虑使用 Intl.DateTimeFormat 来代替:
//using the locale "en-GB" ensures we get day/month/year.
let formattedDate = new Intl.DateTimeFormat("en-GB", {
day: "2-digit",
month: "2-digit",
year: "2-digit"
}).format(dateObject);
// "DD/MM/YY"
formattedDate = formattedDate.replaceAll("/", ".");
// "DD.MM.YY"