[英]How can I obtain a yyyy-mm-dd HH:mm:ss string from a Date object in pure old JavaScript?
[英]How can I convert a HH:mm:ss string to a JavaScript Date object?
我有HH:mm:ss
格式的動態字符串(例如18:19:02
)。 如何將字符串轉換為 JavaScript 日期對象(在Internet Explorer 8 、Chrome 和 Firefox 中)?
我嘗試了以下方法:
var d = Date.parse("18:19:02");
document.write(d.getMinutes() + ":" + d.getSeconds());
您不能僅從HH:mm:ss
類的時間直接創建日期對象。
但是 - 假設您想要實際日期(天)或者對您的情況無關緊要 - 您可以執行以下操作:
let d = new Date(); // Creates a Date Object using the clients current time let [hours, minutes, seconds] = "18:19:02".split(':'); // Using ES6 destructuring // var time = "18:19:02".split(':'); // "Old" ES5 version d.setHours(+hours); // Set the hours, using implicit type coercion d.setMinutes(minutes); // You can pass Number or String. It doesn't really matter d.setSeconds(seconds); // If needed, adjust date and time zone console.log(d.toString()); // Outputs your desired time (+current day and timezone)
現在您有一個 Date 對象,其中包含您指定的時間以及您客戶端的當前日期和時區。
試試這個(沒有 jQuery 和日期對象(這只是一個時間)):
var
pieces = "8:19:02".split(':')
hour, minute, second;
if(pieces.length === 3) {
hour = parseInt(pieces[0], 10);
minute = parseInt(pieces[1], 10);
second = parseInt(pieces[2], 10);
}
由於缺少日期部分,Date 對象從未正確設置。 這應該有效:
var d = new Date("1970-01-01 18:19:02");
document.write(d.getMinutes() + ":" + d.getSeconds());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.