简体   繁体   中英

Nuxt.js date time format

I have this html:

<template>
    <div>
        <div class="card text-center">
            <h2><strong>Title: </strong>{{story.title}}</h2>  
            <p><strong>Score: </strong>{{story.score}}</p>  
            <p><strong>Author: </strong>{{story.by}}</p>  
            <p><strong>Date: </strong>{{ formatDate(story.time) }}</p>
            <!--<p><strong>Date: </strong>{{ dateFormat(new Date(story.time*1000),v) }}</p> -->   
            <NuxtLink :to="`/${story.id}`">
            <p class="btn my-4">View details</p> </NuxtLink>
        </div>
    </div>
</template>

and this scripts:

<script setup>
const { story } = defineProps(['story']) 
    export default {
        
        data () {
            return {
            time: 0,
            }
        },
        methods: {
            formatDate(time) {
                date = new Date(time).format("YYYY/MM/DD")
                return date
            }
        }
    }
</script>

I am not getting this kinda date format: "YYYY/MM/DD". Please help how can I do that in Nuxt.js?

AFAIK, there isn't a single function call to achieve that. I would suggest you re-writing your formatDate using Date.toLocaleString to have full control of your format.

In addition, do not use export default in your <script setup> . It's not a valid syntax.

<script setup>
// Your other setup

function formatDate(time) {
    const date = new Date(time);
    
    // Get year, month, and day part from the date
    const year = date.toLocaleString("default", { year: "numeric" });
    const month = date.toLocaleString("default", { month: "2-digit" });
    const day = date.toLocaleString("default", { day: "2-digit" });
    
    return `${year}/${month}/${day}`;
}
</script>

You could use dayjs (tested with Nuxt 2.15)

yarn add @nuxtjs/dayjs
    export default {
      // ...
      modules: [
        '@nuxtjs/dayjs'
      ],

    <template>
    <div>
    {{ $dayjs(new Date()).format('YYYY/MM/DD') }}
    </div>
    </template>

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.

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