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

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

What is the best way to create a summary module that consolidates and re-exports all the exported functionalities from multiple sub-modules in E

Is there a way to re-export the exports from multiple files in an ESM module without manually listing each export? I am looking to convert my CommonJS module directory, which contains several files, to ESM imports/exports. Currently, I have an index.js fi ...

What is the process for including a static file on an http server?

Looking to create a chatroom using node.js. Utilizing the socket.io template for this project. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require(&ap ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

Resizing the Vue page to fit the viewport and using Flexbox to anchor the footer to the bottom

My Vue.js page structure consists of a navigation bar, main body content, and a footer: <template> <div class="flex_container"> <div class="container_navigation"> <nav-bar /> </div> < ...

What is the most effective way to dynamically incorporate external input into a SlimerJS script?

Could use some assistance with SlimerJS. My current program requires intermittent input from stdin to proceed with the next task. The code below functions effectively when using PhantomJS+CasperJS for reading external input, but encounters difficulties wi ...

Guide on waiting for AWS assumeRole before proceeding with defining the module

I'm currently working on a module that needs to export functions and variables, but before it can do that, it must switch user roles. Here is the code snippet I've come up with. What I need is for the anonymous async function to execute first, an ...

In a JavaScript project, encountering an error when using FB.logout that states "The expression is undefined and not a function."

Seeking to integrate Login with FB into my react website. FB.init({ appId : app_id, cookie : true, xfbml : true, version : 'v5.0' }); Followed by FB.getLoginStatus(({status}) => { if (status === 'conn ...

Tips for personalizing the error message displayed on Webpack's overlay

Is there a way to personalize the error overlay output message in order to hide any references to loaders, as shown in this image: Any suggestions on how to remove the line similar to the one above from the overlay output? ...

Trouble displaying AngularJS $scope.data in the HTML code

I'm experiencing an issue where the data received from a POST request is being logged in the console, but is not displaying on the HTML page. Despite having a controller set up, the {{user}} variable is not appearing on the HTML page. While I can se ...

I have found that I can load a CSS file using Node Express, however, it seems to be malfunctioning. On the other hand, some

I have added app.use(express.static(path.join(__dirname, 'public'))); to my app.js file. Now I am using bootstrap.css along with my custom CSS file main.css. index.html: ┊ <meta http-equiv="Content-Type" content="text/html; charset=UTF- ...

Repurpose the identical popup window

I am searching for a solution to use the same pop-up window whenever it is called. Currently, I need to submit a form into a pop-up window and it works well, except in Chrome iOS where each form submission opens a new tab/window instead of reusing the prev ...

JavaScript: Incorporating an operator into a specific object (instead of the entire class)

Are you familiar with how to include an operator in an object (rather than the entire class)? When it comes to a method, I know you can achieve that by: my_object.new_function = function(){return 1}; Then invoking my_object.new_function() will output ...

Tips for avoiding the display of the overall scrollbar while utilizing grid with an overflow:

In my react-redux application, I am utilizing the material ui Grid component for layout design. The structure of my code is as follows: <div> <Grid container direction="row" spacing={1}> <Grid item xs={3}> ...

What is the best way to ensure that the div from the header file remains fixed directly above the fixed div from another file?

This is the header section that I want to keep fixed within the "header" div. <div id="header" style="display:block;"> <table style="width:100%"> <tr> <td class="col-sm-6" style="background-color:lavender;"><a href ...

Issue with GLTF Loader Trial: Encountering TypeError when trying to resolve module specifier "three". Invalid references detected; relative references must begin with either "/", "./", or "../"

I'm relatively new to working with three.js and I am currently attempting to load a model into my canvas. However, when I import the GLTFLoader, I encounter the error message mentioned in the console above. Despite checking the syntax and relative pat ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: The challenge I am facing involves updating the language of the chips based on the selection made in a dropdown menu. A ...