我只是想以以下格式获取日期和时间。在JS中看起来非常困难和复杂。
2019-06-27 01:06:34.947
英国时间,日期,小时分钟和秒是最重要的,毫秒不是必需的。
每当我尝试时,我都会使用UTC时间,也不需要显示PM / AM等。
var today = new Date().toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric'
//hour: '2-digit',
//minute: '2-digit',
//second: '2-digit'
})
console.log('today', today)
var time = new Date().toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
console.log('time', time)
//var date = new Date();
//var timestamp = date.getTime();
var mytime = today + " " + time;
console.log('mytime', mytime)
//var tt = new Date().toLocaleString().replace(",","").replace(/:.. /," ");
var currentdate = new Date();
var datetime = currentdate.getDate() + "/" +
(currentdate.getMonth() + 1) + "/" +
currentdate.getFullYear() +
currentdate.getHours() + ":" +
currentdate.getMinutes() + ":" +
currentdate.getSeconds();
console.log('datetime', datetime)
X = new Date().toLocaleDateString();
Y = new Date().toLocaleTimeString('en-GB', {
hour: "numeric",
minute: "numeric"
});
mynew = X + " " + Y;
console.log('mynew', mynew)
我希望看到2019-06-27 01:06:34.947或27-06-2019 01:06:34.947
答案 0 :(得分:1)
我想说,将本地Date
实例格式化为 YYYY-mm-DD HH:MM:SS 的最佳选择是自己构建字符串
const today = new Date()
const formatted =
`${
today.getFullYear()
}-${
String(today.getMonth()+1).padStart(2, '0')
}-${
String(today.getDay()).padStart(2, '0')
} ${
String(today.getHours()).padStart(2, '0')
}:${
String(today.getMinutes()).padStart(2, '0')
}:${
String(today.getSeconds()).padStart(2, '0')
}`
// this just displays it
document.querySelector('pre').textContent = formatted
<pre></pre>
像Moment.js这样的库使这种事情变得容易得多。
moment().format('YYYY-MM-DD HH:mm:ss')