警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800
如何获得日期格式为2009/12/30?
警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800
如何获得日期格式为2009/12/30?
当前回答
var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
因为月份索引是以0为基础的,所以必须加1。
Edit
有关日期对象函数的完整列表,请参见
Date
getMonth()
根据当地时间返回指定日期中的月份(0-11)。
getUTCMonth()
根据世界时返回指定日期中的月份(0-11)。
其他回答
它将从用户的浏览器设置中收集语言
使用选项对象中的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()
不错的格式化插件:http://blog.stevenlevithan.com/archives/date-time-format。
你可以这样写:
var now = new Date();
now.format("yyyy/mm/dd");
使用Date获取方法。
http://www.tizag.com/javascriptT/javascriptdate.php
http://www.htmlgoodies.com/beyond/javascript/article.php/3470841
var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();
ES2018引入了正则表达式捕获组,你可以用它来捕获日、月和年:
const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);
这种方法的优点是可以捕获非标准字符串日期格式的日、月、年。
引用https://www.freecodecamp.org/news/es9——javascripts -状态- -艺术-在- 2018 - 9 - a350643f29c/
一行,使用解构。
创建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}`;