警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800
如何获得日期格式为2009/12/30?
警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800
如何获得日期格式为2009/12/30?
当前回答
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
作为参考,你可以看到下面的细节
new Date().getDate() // Return the day as a number (1-31)
new Date().getDay() // Return the weekday as a number (0-6)
new Date().getFullYear() // Return the four digit year (yyyy)
new Date().getHours() // Return the hour (0-23)
new Date().getMilliseconds() // Return the milliseconds (0-999)
new Date().getMinutes() // Return the minutes (0-59)
new Date().getMonth() // Return the month (0-11)
new Date().getSeconds() // Return the seconds (0-59)
new Date().getTime() // Return the time (milliseconds since January 1, 1970)
let dateObj = new Date(); let myDate = (dateObj.getUTCFullYear()) + “/” + (dateObj.getMonth() + 1)+ “/” + (dateObj.getUTCDate()); console.log(myDate)
其他回答
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/
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
或者你可以设置新的日期并给出上面的值
下面是一个使用模板字面值获取年/月/日的更简洁的方法:
var 日期 = 新日期(); var formattedDate = '${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}'; 控制台.log(格式化日期);
我使用这个工作,如果你传递它一个日期obj或js时间戳:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}
欧洲(英语/西班牙语)格式 如果你也想知道今天的日期,你可以用这个。
function getFormattedDate(today)
{
var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var day = week[today.getDay()];
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hour = today.getHours();
var minu = today.getMinutes();
if(dd<10) { dd='0'+dd }
if(mm<10) { mm='0'+mm }
if(minu<10){ minu='0'+minu }
return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}
var date = new Date();
var text = getFormattedDate(date);
*对于西班牙语格式,只需翻译WEEK变量。
var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
输出:周一- 16/11/2015 14:24