Using the JavaScript moment library, you can easily convert a value into seconds

Could moment.js be used to format var timeValue = '65' into 01:05? While easier to format as ('HH:MM:SS'), passing a variable as 65 and converting it into ('mm:ss') results in '01:00' instead of '01:05'.

Check it out

<div id="app">
  <p>
  The time is {{roomTime}}
  </p>
  <br/>
  <p>
  How can we display 01:05 instead of 01:00
  </p>
 </div>

Procedure

new Vue({
  el: "#app",
  data() {
    return{
     roomTime: '',
    }
  },
  mounted: function(){
    var timeValue = '65'; /** Since 65 equals 1 minute and 5 seconds **/
    var formatTime = moment(timeValue).format("MM:SS");
    /** Is there a way to have 65 displayed as 01:05 **/
 
    this.roomTime = formatTime;
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})

Here's my code snippet on JSFIDDLE

https://jsfiddle.net/ujjumaki/2x1ndpja/13/

Answer №1

Hello there! To achieve the desired result, you can utilize the moment library like so:

let timeValue = '65';
moment().startOf('day')
    .seconds(timeValue)
    .format('mm:ss'))

To clarify, first obtain the current date at the beginning of the day (moment().startOf('day')), then include the specified number of seconds stored in timeValue (.seconds(timeValue)), and finally format the output as minutes and seconds (.format('mm:ss')).

The resulting value will be 01:05. Check out the modified code here.

Answer №2

When using the <a href="https://momentjs.com/docs/#/parsing/string/" rel="nofollow noreferrer">moment(String) function</a>, it will first check for known ISO 8601 formats and then RFC 2822 Date time format. If neither match, it will default to parsing with <code>new Date(string)
.

The string "65" is parsed as midnight UTC on Jan 1st 1965. When formatted as mm:ss, it becomes 00:00.

In addition to strings, moment(...) can also accept numbers, treating them as unix timestamps in milliseconds. For example:

const seconds = 65

const ms = seconds * 1000

moment(ms).format('mm:ss')

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

Does the useState hook have any connection to hoisting in React?

I am relatively new to React.js and JavaScript, currently working on a project where I need the ability to manually update my components as needed, due to limitations with a third-party library. After doing some research, I came across a pattern on the of ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

Load the scripts only if they have not already been loaded, and proceed to utilize them

Currently, I have a situation where I must load 4 javascript libraries if they have not been loaded already, and then proceed to utilize their functions. However, I am encountering an issue with Uncaught ReferenceError: sbjs is not defined. Even though th ...

utilizing vue-router for navigating to various pages

I have been working on a Vue application that performs simple inserts, and I am currently exploring the use of Vue Router to navigate between different pages. For example, when I access /postComponent and /userComponent, I want them to load on separate pag ...

A tutorial on creating dynamic text animations: sliding text effects on web pages

Does anyone know how to create a sliding in and out effect like the one on this page: ...

I am receiving the same URL for multiple files stored on Firebase Storage

After attempting to upload multiple files to Firebase Storage and retrieve the download URL for each one, I encountered an issue where all files were successfully uploaded but only the URL for the last file was retrieved. The following code snippet shows ...

AngularJS version 1.3 faces issues with updating bindings when a controller without $scope retrieves data from a webapi

After checking out the link provided below, I noticed that in Angular 1.3 they advise against using '$scope.x' inside the controller and instead suggest using 'this.x' https://docs.angularjs.org/api/ng/directive/ngController The issue ...

Posting data using an Ajax form submission without the need for page

After numerous attempts, I am still facing an issue where clicking the Submit button causes the page to refresh. What changes should I make to resolve this problem? <script> $('#submit').on('submit', function(event) { event.pre ...

Send an API request to update a table in a Vue.js application

I am currently learning about VUE and have a simple API request that provides information on bitcoin prices. I would like to update the table every second and am seeking the easiest way to achieve this. Below is the code snippet: async mounted() { const re ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Why isn't the Ajax send function triggering?

Every time I execute this file, the code runs smoothly until it reaches the point where the send function is triggered. However, the send function only works if there is an alert function directly following it. If I remove the alert("sent"), it gives me a ...

Having an issue with utilizing the useState hook in ReactJS for implementing pagination functionality

I'm struggling to resolve an issue with the React useState. What I'm trying to achieve is making an API call to fetch movies with pagination, but for some reason one of my states is showing up as undefined and it's puzzling me. The component ...

WebClient executes JavaScript code

On my aspx page, there are JavaScript functions that handle paging. I am currently using the WebBrowser control to run these JavaScript functions by calling WebBrowser1_DocumentCompleted. WebBrowser1.Document.Window.DomWindow.execscript ("somefunction(); ...

Struggling to remove the image tag from the jQuery ajax response

My web app is designed to send an ajax post request to a PHP script, which then returns a chunk of HTML data. This HTML includes an image and a table of information. The challenge I'm facing is how to extract the image from the rest of the HTML so tha ...

"Divs are now linked and drag as one cohesive unit instead of

As I was experimenting with making images draggable and resizable, I encountered a small issue. When I attempted to drag two or more images, they would merge into one large draggable object instead of remaining separate. My goal was to make each image drag ...

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

execute a function after submitting the form

I need to implement a function that will be triggered when submitting a form. This function should work for all forms contained within the div with the id "#js_ajax_form". ( The JavaScript code functions properly in Chrome console // Here is the HTML sni ...

Executing a Javascript function when a form is submitted

function validateForm() { alert("Form submitted successfully"); return true; } <form onsubmit="return validateForm()" action="add.php" method="post" id="p1"> <center>Add New Survey</center> <p>&nbsp;&l ...

Using an onClick event along with jQuery to change the CSS class style of another div

After searching extensively without success, I decided to register and ask my first question here. Hopefully, someone can provide a solution: My goal is to create a set of five buttons (divs) with onClick events that will show five different divs. I' ...

Unable to update div CSS using button click functionality

I have been working on this HTML/CSS code and I am trying to change the style of a div using a JavaScript button click event so that the div becomes visible and clickable. However, despite my efforts, it doesn't seem to be working as expected. Whenev ...