I am doing a react project.I want to display today's date and time as "9 am" .This has to be remained unchanged till time is 9 am on next day. After that it should display time as 9 am along with date of that day and continue this till next day 9 am and so on.
<span>Last Updated: {moment().format('MMMM Do YYYY,') " 9:00 am"}</span>
The above code displays the time as 9 am even before the time is 9 am on the nextday. It should look like current time and date gets updated only at 9 am everyday.
CodePudding user response:
Is that what you are looking for? ;)
const getLastStartOfDay = (startOfDayHour) => {
let todayStartOfDay = new Date();
todayStartOfDay.setHours(startOfDayHour, 0, 0, 0);
let yesterdayStartOfDay = new Date(todayStartOfDay);
yesterdayStartOfDay.setDate(yesterdayStartOfDay.getDate() - 1);
let dt = new Date();
const displayDate =
dt.getHours() < startOfDayHour ? yesterdayStartOfDay : todayStartOfDay;
return displayDate;
};
console.log("LastStartOfDay: ", getLastStartOfDay(9));
CodePudding user response:
This code creates a function that retrieves the formatted date at a given hour. If the hour is not specified, it will use the current hour. It will return today's date, unless the hour is before 9, in which case it will return yesterday's date. The format will use the current user's native formatting for a "long" date. The HTML shows the desired result, the console logs what happens before 9 on the current day, and the current hour. The hour is determined by the user's time zone.
function getDateAtNine(forceHour) {
let now = new Date();
const hour = forceHour == null ? now.getHours() : forceHour;
if (hour < 9) {
now = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
}
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'long'
}).format(now);
}
console.log(getDateAtNine(8)); // shows what will print at 8 am on today's date
console.log(getDateAtNine()); // shows what will print at the current hour on today's date
document.querySelector('#dateat9').textContent = getDateAtNine();
<span id="dateat9"></span><span id="nineam">, 9:00 am</span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>