Adjust the time display to show in the format of hours, minutes, and seconds

In my Django API served with django-rest-framework, I am sending a movie object along with its related information to a Vue app. One piece of information included is the movie duration.

Movie Object:

{
    "movie_id": 13,
    "duration": "17:52:14",
    ...
    ...
},

Component Template:

<div id="movieDetailSynopsis">
    ...
    ...
    <p>Duration: {{movie.duration}}</p>
</div>

The duration is in the format

HH:MM:SS

eg: 02:22:08

However, I would like it to be displayed as

2h 22m

Is there a way to achieve this formatting in either Django, Vue.js, or JavaScript?

Update:

I attempted to use a global filter

Main.js:

new Vue({
    router,
    components: {App},
    template: '<App/>',
    store,
    filters: {
        durationFormat(value) {
            const duration = moment.duration(value);
            return duration.hours() + 'h ' + duration.minutes() + 's';
        }
    }
}).$mount('#app');

Inside the component template:

<div id="movieDetailSynopsis">
    ...
    ...
    <p>Duration: {{movie.duration | durationFormat}}</p>
</div>

But I encountered an error:

[Vue warn]: Failed to resolve filter: durationFormat (found in anonymous component - use the "name" option for better debugging messages.)

Answer №1

If you're looking to enhance your Vue application, consider utilizing a Vue filter. For more information on filters, check out the details here. Filters can be registered either globally or locally within your component.

Take a look at an example of a global filter below:

Vue.filter('formatTime', function(value) {
  if (value) {
    const parts = value.split(":");
    return +parts[0] + "h " + +parts[1] + "m";
  } else {
    return "unknown"
  }
});

Here's how you can implement this filter in your template:

<p>Duration: {{movie.duration | formatTime}}</p>

Keep in mind that you can tailor the formatting function to suit your needs. The provided sample is just a starting point to illustrate how filters can be used effectively in Vue. Additionally, consider exploring the capabilities of the moment.js library for advanced date/time handling.

Check out this codepen example, which incorporates moment.js as well.

Update (in response to comment)

To register the filter in your main.js file, you can follow this approach:

// register global filter
Vue.filter('durationFormat', function(value) {
  const duration = moment.duration(value);
  return duration.hours() + 'h ' + duration.minutes() + 's';
});

new Vue({
    router,
    components: {App},
    template: '<App/>',
    store,
}).$mount('#app');

Answer №2

One way to achieve this is by implementing a simple JavaScript code:

var currentTime = "02:22:08";
var convertedTime = parseInt(currentTime.split(':')[0]) + 'h' + ' ' + parseInt(currentTime.split(':')[1]) + 'm';

Answer №3

If you're looking for a different approach, consider using the format() method in JavaScript.

function customFormat(time){
        return time.replace(/(?:0)?(\d+):(?:0)?(\d+).*/,'$1h $2m');
}

["20:45:30","05:15:10"].forEach(function(time){
  console.log(time+" ==> "+customFormat(time));
});

Answer №4

You have the ability to create your own custom template tag in Django:

from django import template

register = template.Library()

@register.simple_tag
def convert_time(value):
    t_list = [t for t in value.split(':')]
    return '{}h {}m'.format(int(t_list[0]), t_list[1])

Once you've created your custom tag, you can easily incorporate it into your templates:

{% load your_tags %}
<div id="movieDetailSynopsis">
  ...
  ...
  <p>Duration: {{movie.duration|convert_time}}</p>
</div>

To learn more about creating custom tags, refer to the Django documentation.

Answer №5

If you want to customize how duration is displayed in Django, you can create a tag filter and add it to your tagfilter.py file:

from django import template
register = template.Library()

@register.filter
def tagFilter(duration):
    d = duration.split(":")
    hh,mm,ss = d[0],d[1],d[2]
    return "%sh %sm %ss" % (hh,mm,ss) # If you prefer not to display seconds, you can remove them:
    # "%sh %sm" % (hh,mm)

In your Django template, use the tag filter like this:

<div id="movieDetailSynopsis">
...
...
<p>Duration: {{movie.duration|tagFilter}}</p>

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 way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Tips for displaying average progress using a progress bar

I'm in the process of creating a website and I would like to incorporate a progress bar that reflects the average of all the input numbers obtained from an HTML form. Although I have some experience with JavaScript, I am currently in need of the Java ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

Proficient in transforming arrays into objects

Having difficulty with a particular javascript problem. Is there a way to approach it in this manner? // Given the input data, I aim to produce output as shown below const ListValues = ["id", "name", "description"] // Expected output const initialValue ...

I would greatly appreciate it if someone could provide an explanation of how Automatic Global Registration of Base Components works in

I've been trying to understand the automatic global generation of base components through the documentation, but I find it confusing. Can someone provide a detailed explanation? ...

What are the benefits of using Wagtail's ModelAdmin inline feature?

Currently, I am utilizing Wagtails' ModelAdmin module (different from Django ModelAdmin) to incorporate a custom Order model into the Wagtail admin. This particular model contains a foreign key that links to a custom Address model. My goal is to show ...

How to Use $scope within a Function in AngularJS

When a page is loaded, I run the following function: $scope.showTags = function(Id) { $scope.toggleSelectedBlocks = function selectB(block) { // There is a checkbox to be selected... } $scope.greetUser() { console.log("GREETIN ...

Avoid triggering the parent modal to close when a child element is clicked in VueJS

In my Vue application, there is a situation where I have a button called "detach button" with a @click function inside an element that is clickable. When clicking on this parent element, it triggers another @click function and toggles a Bootstrap modal eve ...

Seeking assistance with setting up BxSlider installation

I'm struggling with adding bxslider to my HTML template. No matter what I try, the slider doesn't work as expected. When I preview my website, all three images are displayed together in a single column. Can someone please guide me on how to fix t ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

React: Basic To-Do List Application, Issue with Checkbox Not Refreshing

Currently working on a React project to improve my skills. Everything is running smoothly except for the issue with the checked box not updating when clicked. It seems like the state of the app isn't being updated correctly. Any assistance would be gr ...

The significance of using `jshint globalstrict: true` alongside 'use strict'

It's quite common for me to come across these two lines at the beginning of JavaScript source code. /* jshint globalstrict: true */ 'use strict'; While I understand the significance of 'use strict';, I am curious about why jshint ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

Showing data from a JavaScript controller's JSON response in an HTML table

I'm currently developing a spring app using AngularJS and I have a response coming from a JS controller. My goal is to showcase this response in a table on the webpage. The object devDebtTable is accessible to the page from the JS controller. The JS ...

When attempting to launch the Ember Cordova application on the mobile device, an error was encountered stating: "Unable to access property 'notification' as it is

After installing cordova-plugin-local-notifications and trying it again, I encountered an error on the following line of code: cordova.plugins.notification.local.on("click", function (notification) { The error message reads: Error while processing rou ...

How to extract data from an alert in an Ionic application

I am currently working with Ionic 3 and I have a requirement to implement autocomplete using Google Maps on an input field. Below is the alert that I have in my .ts file: let alert = this.alertCtrl.create({ title: 'Offer a Ride', inputs: ...

What are the steps to display a graph on a webpage using AJAX in Django?

I'm currently working on developing a weather forecast application, and I have implemented a date input box on the home page. When users enter a date and click submit, a graph displaying temperature data should be displayed. I have set up a URL that r ...

Error in syntax: An unexpected token was encountered during an AJAX request

I am currently working on a project that involves looping through multiple JSON files within a directory called "trips" and extracting data from each file to display on the front end of the website. However, I'm encountering a persistent error message ...