Format a date string in javascript

后端 未结 7 1522
误落风尘
误落风尘 2020-12-03 15:26

Hello every i have date field of type string with iso format like this: const date = \"2017-06-10T16:08:00: i want somehow to edit the string in the following format like th

相关标签:
7条回答
  • 2020-12-03 16:07

    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"));

    0 讨论(0)
  • 2020-12-03 16:11

    Use Moment.js and the .format function.

    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.

    0 讨论(0)
  • 2020-12-03 16:18

    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
    
    0 讨论(0)
  • 2020-12-03 16:18

    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:

    0 讨论(0)
  • 2020-12-03 16:19

    If the date string is always in ISO format, you can also use regex to reformat without other library:

    date.replace(/(\d{4})\-(\d{2})\-(\d{2}).*/, '$3-$2-$1')
    
    0 讨论(0)
  • 2020-12-03 16:22

    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}`)
    
    0 讨论(0)
提交回复
热议问题