Как обновить Intl.DateTimeFormat() с новой датой?

#javascript

#javascript

Вопрос:

У меня возникли некоторые проблемы с созданием часов

 let format = new Date();
let time;
let timeBtn = document.querySelector("#time");

options = {
    year: 'numeric', month: 'numeric', day: 'numeric',
    hour: 'numeric', minute: 'numeric', second: 'numeric',
    hour12: true,weekday : 'short'
};
time = new Intl.DateTimeFormat('en-US', options).format(format);
timeBtn.innerHTML = time;
setInterval(updateTime,1000);
console.log("updatecalled");
function updateTime(){
    time = Intl.DateTimeFormat('en-US', options).format(format); ///not updating

    timeBtn.innerHTML = time;
   
}
  

Когда я обновляю браузер, время указано правильно, даже секунды, но когда я пытаюсь его обновить, время остается неизменным и не меняется, код в функции UpdateTime() выполняется каждую секунду. пожалуйста, помогите

Ответ №1:

Я добавил несколько аннотаций. Кажется, есть пара основных недоразумений:

  • Именование переменных. Например, format это дата-время, а не формат. time — это форматированная строка даты и времени.
  • Объявление переменных в областях, где они не требуются (ни format ни time не нужно объявлять вверху)
  • Это не вызывает ошибку, но не объявляйте переменные без ключевого слова let или const — это загрязняет глобальную область видимости и window объект.

 /* We don't need to initialize these up here */
// let format = new Date();
// let time;

/* Use `const` for variables that don't need to be reassigned */
const timeBtn = document.querySelector("#time");

/* Always use `const` or `let` to declare variables */
const options = {
    year: 'numeric', month: 'numeric', day: 'numeric',
    hour: 'numeric', minute: 'numeric', second: 'numeric',
    hour12: true, weekday : 'short'
};

/* We might as well initialize this up here,
   as we don't need a new instance each time the function is called
   (the `options` don't change) */
const formatter = new Intl.DateTimeFormat('en-US', options);

/* Just call the function once - no need to repeat the same code here */
// time = new Intl.DateTimeFormat('en-US', options).format(format);
// timeBtn.innerHTML = time;

/* Call the function once when our code loads... */
updateTime();
/* ...then periodically at intervals of 1000 ms */
setInterval(updateTime, 1000);

// console.log("updatecalled");
/* `updateTime` wasn't called here in your original code, so not clear
   what this log statement was for */

function updateTime() {
    /* Don't name this variable `format` - it's a datetime, not a format */
    const dateTime = new Date();
    const formattedDateTime = formatter.format(dateTime);

    /* `formattedDateTime` is a normal string, not HTML, so we should
       set the element's `textContent`, not `innerHTML` */
    timeBtn.textContent = formattedDateTime;
}  
 <button id="time"></button>  

Ответ №2:

Это связано со значением format , установленным на определенную дату ОДИН раз. Вы должны вызвать new Date() внутри вашей updateTime функции

 let format = new Date();
let time;
let timeBtn = document.querySelector("#time");

options = {
    year: 'numeric', month: 'numeric', day: 'numeric',
    hour: 'numeric', minute: 'numeric', second: 'numeric',
    hour12: true,weekday : 'short'
};
time = new Intl.DateTimeFormat('en-US', options).format(format);
timeBtn.innerHTML = time;
setInterval(updateTime,1000);
console.log("updatecalled");
function updateTime(){
    time = Intl.DateTimeFormat('en-US', options).format(new Date()); /// use new Date() here

    timeBtn.innerHTML = time;
   
}
  

Ответ №3:

В идеале вам нужно wrap format использовать функцию и получать return dateFormat каждый раз, когда вы хотите то же самое DateTimeFormat

Как только вы загружаете страницу, она сначала DateTimeFormat форматирует дату, но setInterval формат не будет обновляться, поскольку он уже был, loaded поэтому вам нужен function с return new date() format с с, из него.

Если вы хотите использовать new Date только один раз и не делать ничего repetition , вы можете добавить let format = new Date(); внутри dateFormat() функции, и это тоже сработает.

Живая рабочая демонстрация:

 let format = new Date();
let time;
let timeBtn = document.querySelector("#time");

let options = {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: true,
  weekday: 'short'
};

//formmatter
let dtFormatter = new Intl.DateTimeFormat('en-US', options)

//Set initial
time = dtFormatter.format(format);
timeBtn.innerHTML = time;

//format
function dateFormat() {
  let currDate = new Date();
  let date = dtFormatter.format(currDate);
  return date //callback
}

function updateTime() {
  time = dateFormat()
  timeBtn.innerHTML = time;
}

//setInterval
setInterval(updateTime, 1000);  
 <div id="time"></div>