[英]How to convert JavaScript Date object to string that is compatible with datetime-local input?
基本上我有一個 Date 對象。 如何將其轉換為與datetime-local
格式yyyy-MM-ddThh:mm兼容的字符串?
我嘗試了Date.toISOString
方法,但它不起作用,因為它在末尾附加了.SSSZ
。 給我以下輸出The specified value "2017-04-10T17:02:00.320Z" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
The specified value "2017-04-10T17:02:00.320Z" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
.
有沒有人有任何干凈的解決方案來解決這個問題?
我使用moment.js庫相應地格式化日期。 這行代碼可以解決問題moment(date).format("YYYY-MM-DDTkk:mm")
。
要么theDate.toISOString().substring(0, 16)
,要么使用getFullYear
、 getUTCDate
、 getUTCMonth
(記住它從 0 開始)等方法自己構建字符串。 或者使用圖書館來做到這一點。
我遇到了同樣的問題,但我不想使用 moment 或任何其他大庫來進行簡單的計算。
我只是使用了 ISO 日期但添加了時區偏移量,因此在使用箭頭導航日期值時輸入不會變得瘋狂。
const offset = new Date().getTimezoneOffset() * 1000 * 60
const getLocalDate = value => {
const offsetDate = new Date(value).valueOf() - offset
const date = new Date(offsetDate).toISOString()
return date.substring(0, 16)
}
基本上它會添加時區偏移量並將其轉換為 ISO 日期,但隨后我們使用子字符串 (0, 16) 去除時區
這為我們提供了正確的“時區 ISO”日期。
我正在嘗試,但到目前為止它工作正常。 我希望這在本地得到解決,奇怪的是它不能開箱即用。
使用moment.js
將日期格式化為相應的日期:
moment(new Date()).format('YYYY-MM-DDTHH:mm')
但不是: moment(date).format("YYYY-MM-DDTkk:mm")
之前的答案是錯誤的!!
kk 介於 1 - 24 之間(與本地 DateTime 文本字段不兼容)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.