Vue.js live timestamp update

I have a function that returns the current timestamp with date and time, but it remains static upon page load without updating (meaning: the seconds and minutes do not change in real-time).

Desired Outcome: I want the time to be continuously moving and not static.

Code

script

methods: {
  currentDateTime() {
      const current = new Date();
      const date =
        current.getFullYear() +
        "-" +
        (current.getMonth() + 1) +
        "-" +
        current.getDate();
      const time =
        current.getHours() +
        ":" +
        current.getMinutes() +
        ":" +
        current.getSeconds();
      const dateTime = date + " " + time;

      return dateTime;
    },
}

HTML

{{ currentDateTime() }}

screenshot

https://i.sstatic.net/bc0UY.jpg

Any suggestions?

Answer №1

currentDateTime() function will only be called once initially. To have it continuously update, utilize the setInterval() method to execute it every 1 second.

data: {
    timestamp: ''
},
mounted: function () {
    setInterval(() => { this.currentDateTime() }, 1000)
  }
}),
methods: {
  currentDateTime() {
      const current = new Date();
      const date =
        current.getFullYear() +
        "-" +
        (current.getMonth() + 1) +
        "-" +
        current.getDate();
      const time =
        current.getHours() +
        ":" +
        current.getMinutes() +
        ":" +
        current.getSeconds();
      const dateTime = date + " " + time;
      this.timestamp = dateTime;
    },
}

HTML

{{ timestamp }}

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

What is the best approach to concurrently update a single array from multiple functions?

In my React app, I have a form with various input fields and checkboxes. Before making an API call to submit the data, I have functions set up to check if any fields are left blank or unchecked. These check functions are triggered when the form button is ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...

An error is encountered with the 'this' keyword in the map operator of Angular

I am in the process of developing a custom validator for a Slug form control and have encountered an issue with my code. ngOnInit() { this.slugCtrl.setAsyncValidators(this.slugValidator); } slugValidator(control: AbstractControl) { const obs1 = c ...

When utilizing JavaScript to input text, I have observed that if I enter text in one text box, any previously entered value is automatically deleted

Currently, I am facing an issue with 3 text boxes in a row that I am populating using JavaScript. The problem arises when I enter text into one field and then move to the second box to input text - the value from the first text box gets removed. Below is ...

Missing value: Attempted to access properties of an undefined variable

I've been encountering an issue while trying to transfer data from one component to another using a service. The error message that I keep running into is: ERROR TypeError: Cannot read properties of undefined (reading 'statistics') at St ...

Anchor tags fail to function properly due to jQuery interference

I am attempting to modify the class of the li tag on a navbar to active when I am on that page. jQuery successfully changes the li class to active, but the <a> inside it stops functioning. When I deactivate the js file, the anchor tags start workin ...

What is the best way to pass variables to a function in an Angular

How can I pass the variables year and monthGet to a function in an Angular service from a controller? Service myApp.factory('getJsonForCalendarService', function($resource, year, monthGet) { return $resource( '../rest/ ...

JavaScript Generated From TypeScript Encountering TypeError

Why is the JavaScript code produced by this TypeScript snippet causing a TypeError upon execution? class Foo { public foo: { bar: number }; constructor() { this.foo["bar"] = 123; } } new Foo(); Even though I'm compiling it with the ...

the div background is limited to the exact size of the text, not filling the entire

Currently, as I work on my web page using react.js, I'm facing the challenge of implementing a full-size background. Despite my efforts, the background only occupies the size of the text within the div. Here is the snippet of code I am working with: a ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

Retrieve data from AJAX request using array index

A certain script in my possession is able to extract data from a JSON file and store the name property of each element in an array. HTML <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script> var names = []; var f ...

How to prevent horizontal scrolling on the right side of a div element

Greetings! I am relatively new to coding and currently facing an issue with stopping horizontal scrolling when the second div is fully visible on the screen (while keeping the third div hidden). Here is the code snippet I have been working on: $(docum ...

jQuery - preserving the integrity of array members when extending objects

Currently, I am in the process of developing a jQuery plugin where I'm using the common $.extend method to merge user-defined settings with default values. Here is an example: var options = $.extend({ title: '', padding: [0, 0, ...

Emulating the sorting functions in Excel, including "sort by" and "then by" actions

Is there a way to replicate Excel's sorting in JavaScript? Imagine I have an array with the following items: [6,0.75] [6,0.81] [9,0.75] [4,0.20] Sorting them by the first key is straightforward, but how can we achieve "then by" sorting? If we apply ...

Values returned by XmlHttpRequest

When it comes to returning data from an XmlHttpRequest, there are several options to consider. Here's a breakdown: Plain HTML: The request can format the data and return it in a user-friendly way. Advantage: Easy for the calling page to consume ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

Error encountered while executing React-Native run-android command

Encountering a perplexing error in VScode when attempting to run the command React-native run-android in the terminal. I also ran react-native doctor and received all green checkmarks for Node, yarn, android_home, and android sdk 0 errors. Struggling to ...

Retrieve values of data attributes and HTML elements into an array

I have a scenario where I have HTML with specific tags containing data-id values and inner HTML values, and I need to extract them into an array. Is there a way to achieve this using either Jquery or Javascript? <li class="dual-listbox__item" data-id= ...

Tips for preventing the need to re-render every child component generated by the v-for directive

Here is a paragraph about the list of child components: <question-list-item v-for="(item, index) in questionListParsed" :key="item.id" :both-question="item" :class-id="classId" ...