我正在嘗試React使用以下方法更改我的應用程式中的時間setHours:
function App() {
let currHour = new Date().setHours(15);
return (
<div>
<h1>{currHour}</h1>
</div>
);
}
我得到的輸出不是 15 而是:1667813785897。
我如何得到這個意外的輸出?
uj5u.com熱心網友回復:
耦合的東西,currHour是一個Date物件,所以渲染它只會呼叫toString方法,它只會輸出毫秒或其他東西。如果你愿意15,那么你會想要渲染currHour.getHours(). 此外,每次渲染時都currHour將設定為,這可能是不可取的。也許它應該是狀態?還是在一個?我不確定你的用例是什么。new Date().setHours(15)Appref
uj5u.com熱心網友回復:
如果我們查看
所以你收到的結果實際上是預期的。讓我們看一個應該被證明是有用的片段:
let dt = new Date();
console.log(`The current date is ${dt}`);
console.log(`Hours before setting the hours to 15 were ${dt.getHours()}`);
let millisecondsSince1970 = dt.setHours(15);
console.log(`After setting the hours to 15, the modified date is ${dt}`);
console.log(`Hours after setting the hours to 15 are ${dt.getHours()}`);
console.log(`Milliseconds since January 1st 1970 00:00:00 are ${millisecondsSince1970}`);
console.log(`Milliseconds since January 1st 1970 00:00:00 converted back to Date is ${new Date(millisecondsSince1970)}`);
如您所見,我們可以同時獲取日期和時間
因此,setHours您可以執行以下操作將小時數設定為 15 并回傳它們,而不是得到結果:
let currDate = new Date();
currDate.setHours(15);
let currHours = currDate.getHours();
或者,如果您甚至不想設定時間,那么您可以簡單地說
let currHours = new Date.getHours();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/532789.html
