您好,每个我都有这样的 iso 格式的字符串类型的日期字段: const date = "2017-06-10T16:08:00: 我想以某种方式以如下格式编辑字符串:10-06-2017 但我'正在努力实现这一目标。我在“T”字符之后剪切了子字符串
It can be achieved without moment.js, but I suggest you use it
var date = new Date("2017-06-10T16:08:00");
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var formattedDate = day + '-' + month + '-' + year
如果日期字符串始终为 ISO 格式,您还可以使用正则表达式重新格式化,而无需其他库:
date.replace(/(\d{4})\-(\d{2})\-(\d{2}).*/, '$3-$2-$1')
I would like to suggest to use moment js find it - http://momentjs.com/docs/
and use it like
moment(date.toString()).format("MM/DD/YYYY")
You can use the JavaScript date() built in function to get parts of the date/time you want. For example to display the time is 10:30:
<script>
var date = new Date();
var min = date.getMinutes();
var hour = date.getHour();
document.write(hour+":"+min);
</script>
To get the year, month, date, day of week use
getFullYear();
getMonth();
getDate();
getDay();
To get the date you posted:
Using Date.toJSON()
function formatDate(userDate) { // format from M/D/YYYY to YYYYMMDD return (new Date(userDate).toJSON().slice(0,10).split('-').reverse().join('-')); } console.log(formatDate("2017-06-10T16:08:00"));
If you're looking to do this in vanilla javascript, @Ivan Mladenov's answer is great and can be consolidated slightly using padStart .
const date = new Date()
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
console.log(`${day}-${month}-${year}`)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.