Reputation: 1205
I use sapper to save order data to my mongodb. One field save the time the order was entered. I'm trying to display the time of the order on the front to the user dashboard (order name, date and time).
All is working fine except to one js date fn that is giving me error. Let me explain: My code is simple, I use fetch in preloading fn
<script context="module">
export async function preload(page, session) {
const res = await this.fetch(`protectedpageserver`, {
credentials: 'include'
});
let response = await res.json()
return { data: response }
}
</script>
<script>
export let data
</script>
<ol>
{#each data as link}
<li >
<p><b> Order </b> : {link.order} </p>
<p> Date : {link.enteredAt.substring(0, 10)} </p>
<p> Time : {link.enteredAt.substring(11, 19)}</p>
<p>
Time : {link.enteredAt.toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit'
})}</p>
</li>
{/each}
</ol>
The first time substring() fn is working:
<p> Time : {link.enteredAt.substring(11, 19)}</p>
The second time toLocaleTimeString() fn is giving me error
TypeError: link.enteredAt.toLocaleTimeString is not a function
My question is why? I can handle the toLocaleTimeString() on the server route in forEach() and supply the front with the desired time format but this is making me curious to why one fn is working and the second is producing an error despite the fact that both are js date functions. Why this behavior? Can I write the toLocaleTimeString() in a different way to make it work?
Upvotes: 0
Views: 1365
Reputation: 8386
You're passing a string to the function toLocaleTimeString
which is an instance method of the Javascript Date object. I know it's a string since it works with substring()
which expects a string and would not work if you were passing a date object to it.
But assuming that the string link.enteredAt
is in the shape of a date the following would work since Svelte lets you run JS in the curly braces.
<p>
Time : {new Date(link.enteredAt).toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit'
})}</p>
Upvotes: 1