简体   繁体   English

在javascript中格式化日期字符串

[英]Format a date string in javascript

您好,每个我都有这样的 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不用moment.js也可以实现,但是我建议你使用它

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

Use Moment.js and the .format function.使用Moment.js.format函数。

moment('2017-06-10T16:08:00').format('MM/DD/YYYY');

Will output会输出

06/10/2017

Beside the format function Moment.js will enrich you will alot more useful functions.除了format功能之外, Moment.js还会丰富你更多有用的功能。

如果日期字符串始终为 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/我想建议使用moment js找到它 - 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.您可以使用 JavaScript date() 内置函数来获取您想要的部分日期/时间。 For example to display the time is 10:30:例如显示时间是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(); getFullYear();

  • getMonth(); getMonth();

  • getDate();获取日期();

  • getDay(); getDay();

To get the date you posted:要获取您发布的日期:

Using Date.toJSON()使用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 .如果您想在 vanilla javascript 中执行此操作,@Ivan Mladenov 的回答很棒,可以使用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}`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM