How can I change format datetime to date in vue component?

21,895

Solution 1

The best way without a lib really depends on the browser you target. See some possibilities below.

// IE 11 or later
function format(date) {
  var month = date.toLocaleString("en-US", { month: 'short' })
  return date.getDate() + ' ' + month + ' ' + date.getFullYear();
}
// Pretty much every browser
function formatCompat(date) {
  var ms = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return date.getDate() + ' ' + ms[date.getMonth()] + ' ' + date.getFullYear();
}

var d1 = new Date("2018-04-11T12:00:00.000Z");
console.log(format(d1));
console.log(formatCompat(d1));
var d2 = new Date("2010-01-01T12:00:00.000Z");
console.log(format(d2));
console.log(formatCompat(d2));

Solution 2

The best way is to use the filter property of Vue and moment library:

Vue.filter('formatDate', function(value) {
  if (value) {
    return moment(String(value)).format('MM/DD/YYYY hh:mm')
  }
});

That way you can use a pipe to format every date that has been rendered:

<div>
    <p>{{ yourDate | formatDate}}</p>
</div>

For a more samples look at the following links:

Solution 3

You can get the Date by using toLocaleDateString().

If that does not output in the format that you would like then you will want to make your own string contcatenation by using the following

getDate(datetime) {

let date = new Date(datetime);

let dateString = `${date.getFullYear}/${date.getMonth() + 1}/${date.getDate}`

return date
}
Share:
21,895

Related videos on Youtube

Success Man
Author by

Success Man

Updated on April 01, 2020

Comments

  • Success Man
    Success Man about 4 years

    My vue component like this :

    <template>
        ...
            <td>{{getDate(item.created_at)}}</td>
        ...
    
    </template>
    <script>
        export default {
            ...
            methods: {
                getDate(datetime) {
                    let date = new Date(datetime).toJSON().slice(0,10).replace(/-/g,'/')
                    return date
                }
            }
        }
    </script>
    

    If I console.log(datetime), the result : 2018-03-31 18:23:20

    I want to get only date and change the format to be : 31 Mar 2018

    I try like my component above, but the result like this : 2018/03/31

    I try use format method and dateformat method, but it is undefined

    How can I solve this problem?

    • Adriano
      Adriano about 6 years
      Have a look at this library, I don't know if you need to heavily use date formats and conversions, so it might not be the best solution for you, but perhaps you will find some inspiration for your specific issue :) github.com/datejs/Datejs
    • moses toh
      moses toh about 6 years
      @Adriano Is there any other way without libraries?