Reputation: 723
I would like to transform a date with the .toLocaleDateString()
but I can't figure out what is wrong with the code below. I have tried to pass todo.dueAt
to a method defined under the <script>
tag which would return with the transformed date, but I got the same TypeError: todo.dueAt.toLocaleDateString is not a function"
issue.
Why it should be a function at all and why is it work only with the todo.dueAt
?
<template>
<div class="todo-table">
<table>
<thead>
<tr>
<th>Done</th>
<th>Title</th>
<th>Created</th>
<th>Due Date</th>
</tr>
</thead>
<tbody>
<tr v-for="todo in todos" :key="todo.id">
<td> {{ todo.isCompleted}}</td>
<td> {{ todo.title }}</td>
<td> {{ todo.dueAt.toLocaleDateString("hu-HU") }}</td>
<td> {{ todo.dueAt.toLocaleDateString("hu-HU") }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: "TodoList",
props: {
todos: Array
},
method: {
formatDate: (date) => {
return date.getFullYear() + "." + (date.getMonth() + 1) + "." + date.getDate();
}
}
}
</script>
Upvotes: 0
Views: 2857
Reputation: 6005
Edit: The answer assumes the value todo.dueAt is a valid timestamp and can be converted to a Date object directly. Please do not use this if the format of dueAt is not known
One way is to wrap the todo.dueAt with a new Date()
The constructor can wrap even if the parameter is a Date type, so it will ensure that the time is a valid Date object
<tr v-for="todo in todos" :key="todo.id">
<td> {{ todo.isCompleted}}</td>
<td> {{ todo.title }}</td>
<td> {{ todo.dueAt && new Date(todo.dueAt).toLocaleDateString("hu-HU") }}</td>
<td> {{ todo.dueAt && new Date(todo.dueAt).toLocaleDateString("hu-HU") }}</td>
</tr>
Even if the dueAt is already a Date, wrapping it will not create a problem
console.log(new Date(new Date()));
A better solution is to check if the value is an instance of Date() before the operation
(todo.dueAt instanceof Date) ? /*use LocaleDateString*/ : /* Convert and use */
Upvotes: 2