Vue application encountering issues with the functionality of the split method in Javascript

Hey there! I am just starting out with JS and Vue. Currently, I have a Vue application that pulls date information from an open API. The tricky part is that the API response includes both the date and time in one string (for example: 2019-10-15T09:17:11.808545+02:00). I'm trying to separate the date from the time at "TO" but haven't been successful so far. Any tips or guidance on how to achieve this would be greatly appreciated. Here's what my current setup looks like:

<template>
    <div class="content">
        {{split_date(this.date)}}
    </div>
</template>

<script>
    export default {
        mounted() {
            axios.get("http://worldtimeapi.org/api/timezone/Europe/Berlin", {})
                .then(response => {
                    this.date = response.data.datetime;
                })
                .catch((error) => {
                    console.log(error);
                });
        },

        data() {
            return {
                date: "",
                separated_date: [],
            };
        },

        methods: {
            split_date(date) {
                this.separated_date = date.split("TO");
                return this.separated_date[0];
            }
        }
    }
</script>

Currently, the output displays the entire response: 2019-10-15T09:17:11.808545+02:00

I am also encountering an error message saying:

You may have an infinite update loop in a component render function.

Answer №1

In the feedback provided by others, it was mentioned that you are currently splitting on TO instead of T. Remember that your time begins from 0 (zero). Additionally, there is no need to store the separated_date within the data property. Consider utilizing a computed property for automatically recalculating the separated_date whenever the original date changes.

Just a friendly reminder: if you find yourself working extensively with dates and times, it might be beneficial to integrate a library for assistance. Some popular options include date-fns, Luxon, or Moment.js

Answer №2

This question doesn't pertain to Vue specifically, but rather it's about handling and parsing date/time in JS:

const date = new Date('2019-10-15T09:17:11.808545+02:00')

console.log("Date object:", date)

// example date elements:
console.log("Year:", date.getFullYear())
console.log("Month:", date.getMonth() + 1) // Remember that months are zero-based in JS
console.log("Timestamp:", date.getTime())

// To format as YYYY-MM-DD with leading zeroes
const datetime = `${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(-2)}-${("0" + date.getDate()).slice(-2)}`

console.log("YYYY-MM-DD:", datetime)

You can find more information about Date here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Solution for Vue

new Vue({
  el: "#app",
  data: {
    split_date: ''
  },
  methods: {
    async getWorldTime() {
      const resp = await fetch('http://worldtimeapi.org/api/timezone/Europe/Berlin')
      const worldTime = await resp.json()
      return await worldTime.datetime
    }
  },
  async mounted() {
    console.log(await this.getWorldTime())
    const date = new Date(await this.getWorldTime())
    this.split_date = `${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(-2)}-${("0" + date.getDate()).slice(-2)}`
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">{{split_date}}</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

The Discord bot seems to be stuck in time, relentlessly displaying the same start time without any updates in between. (Built with Node.js and Javascript

const Discord = require('discord.js'); const client = new Discord.Client(); var moment = require('moment'); const token = '//not telling you this'; const PREFIX = '!'; client.on('ready', () =>{ con ...

Creating seamless transitions between pages using hyperlinks

On the homepage, there are cards that list various policies with a "details" button above them. Clicking on this button should take me to the specific details page for that policy. However, each product can only have one type assigned to it. For instance: ...

You cannot employ typed arguments in combination with Typescript within the VueJS framework

I'm struggling to develop a typescript vue component with some methods. Here is the script snippet. <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ methods: { check(value: number) { console.log(valu ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Why does Vue prompt me with 'mutate Vuex store state outside mutation handlers' when I try to commit?

<template> <div class="counter-warp"> <p>generate</p> <div class="statusCon"> <p class="card"> last: {{completed.length > 0 ? completed[completed.length - 1].text : ''}} </p& ...

How can AJAX be used for form validation prior to submission?

Currently, I am facing an issue with validation on the client side when making an ajax cross-domain request to my PHP server page. I have a standard HTML form that posts input fields such as name, last name, and message. Here is an example of my form on th ...

Accessing querySelector for elements with numerical values in their name

Here is a URL snippet that I need to work with: <h1 id="header_2" title="mytitle" data-id="header_title" class="sampleclass " xpath="1">mytitle<span aria-label="sometest" class="sa ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

Transforming a TypeScript enum into an array of objects

My enum is defined in this structure: export enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } However, I want to transform it into an object ar ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Utilize AngularJS to retrieve and interact with the JSON data stored in a local file once it has

Please do not mark this as a duplicate since I have not found a solution yet. Any help would be appreciated. I have a file called category.json located next to my index.html file, containing the following JSON data: [{"name":"veg"},{"name","non-veg"}] W ...

Feeling puzzled about the next() function in Node.js?

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js function isAuthenticated (req, res, next) { // If the user is authenticated in the session, call the next() to proceed to the next request handler // Passport adds this met ...

Using inline CSS to apply conditional styles to a component in React is a great way to customize the

I'm currently working on customizing the styles of some buttons depending on their 'active' status and whether the user is hovering over them. So far, it's partially working but I'm encountering behavior that I can't fully com ...

function complete, ajax request finished

When working with Ajax to get data, I encountered a situation where I needed to return the value of `username` from within an if statement that is inside a loop and a function. How can I achieve this? Your help would be appreciated. $.ajax({ ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...

Configurations for developing Nuxt.js single-page applications in the development server

I previously set up the devserver in vue-config.js as shown below: devServer: { proxy: { "/api/*": { target: "http://localhost:3001", secure: false } } } However, this configuration is not working in nuxt-SPA. My frontend continue ...

Encountering a glitch while iterating through function results in failure after the initial modification

I am facing some errors with the script provided below: var sections = ["#general_info", "#address_records", "#employment_history", "#driver_experience", "#military_experience", "#eeo_survey", &qu ...

You can't send headers to the client in Express after they have already been set

I successfully registered and inserted a record in my MongoDB. However, I encountered an error when trying to log in at the line "!user && res.status(401).json("Wrong User Name");" Cannot set headers after they are sent to the client at new NodeError ...

Can someone explain the process of unescaping characters in an API response to me?

I have created an application that leverages AngularJS to pull data from the WP Rest API V2. The response includes escaped characters, like the example below: "excerpt": { "rendered": "<p>When we go shopping, we encounter many different labeling ...