警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800
如何获得日期格式为2009/12/30?
警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800
如何获得日期格式为2009/12/30?
当前回答
一行,使用解构。
创建3个字符串类型的变量:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')
生成3个类型为number (integer)的变量:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))
从那时起,你就可以很容易地以任何你喜欢的方式组合它们:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;
其他回答
我建议你使用Moment.js http://momentjs.com/
然后你可以这样做:
moment(new Date()).format("YYYY/MM/DD");
注意:如果你想要当前的TimeDate,你实际上不需要添加新的Date(),我只添加它作为一个引用,你可以传递一个日期对象给它。对于当前的TimeDate,这也适用:
moment().format("YYYY/MM/DD");
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"
info
如果需要2位数字的月份和日期(2016/01/01 vs 2016/1/1)
code
var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);
输出
2016/10/06
小提琴
https://jsfiddle.net/Hastig/1xuu7z7h/
信贷
更多信息来自这个答案
more
要了解更多关于.slice的信息,w3schools的自己尝试编辑器帮助我更好地了解如何使用它。
它将从用户的浏览器设置中收集语言
使用选项对象中的minutes和hour属性来处理它们。 你可以用长值来表示月份,比如8月23日等等。
function getDate(){
const now = new Date()
const option = {
day: 'numeric',
month: 'numeric',
year: 'numeric'
}
const local = navigator.language
labelDate.textContent = `${new
Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()
下面是一个使用模板字面值获取年/月/日的更简洁的方法:
var 日期 = 新日期(); var formattedDate = '${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}'; 控制台.log(格式化日期);