Angular JS filter for time formatting

I'm looking to reformat the time 06:31:04 to display only in the format hh:mm - like 06:31

I've attempted:

$scope.date = '06:31:04';

<p ng-bind="date | date:'HH:mm'"></p>

However, the time is not formatting correctly.

Any suggestions on how I can achieve this? Thank you

Answer №1

The optimal solution involved creating a custom filter

angular.module('bar', [])
.filter('timeFormat', function ($filter) {
return function (inputTime, outputFormat) {
    var parts = inputTime.split(':');
    var newDate = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
    return $filter('date')(newDate, outputFormat || 'h:mm');
};
});




{{ '06:31:04' | timeFormat }}

Answer №2

For more information, please refer to the official documentation.

<p ng-bind="date | date:"hh:mm"}}></p>

It appears that the format of your date may be incorrect.

A JavaScript Date instance represents a specific moment in time indicated by the number of milliseconds since January 1, 1970 UTC. (source)

Example: 1288323623006. The current format may not be recognized for the filter. Consider trying:

$scope.date = new Date();

If you need to convert a string in the given format to a date object, you can use the following approach:

var dateElements = "06:31:04".split(':');
var date = new Date();
date.setHours(time[0]);
date.setMinutes(time[1]);
$scope.date = date;

You can then apply the desired formatting using the filter.

Answer №3

Below is a straightforward example to demonstrate:

$scope.currentDate = new Date();

In the HTML file, include:

<h2>
    {{ currentDate | date:'hh:mm' }}
</h2>

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

iOS PhoneGap event registration not triggering as expected

My app performs perfectly on android, but I encounter an issue when testing it on a real iOS device. I am unable to register the device in order to obtain the device token. Below is the code snippet: .run(function($ionicPlatform, $rootScope) { $ionicP ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

Accessing data from an API in an AngularJS dropdown menu

After retrieving JSON data from an API, I store it in $scope.industry. $scope.industry = []; $http.get('/industrygroup?languageid=1') .then(function (result) { $scope.industry = result.data; }); The JSON data st ...

Is there a workaround for making Three.js OnDocumentMouseDown compatible with touch screens?

To view the complete code, visit this Glitch project: Within public/components.js, I have defined a custom AFRAME component that enables rotation of an item when dragged with the mouse. AFRAME.registerComponent('drag-rotate-component', { sc ...

Implementing user authentication in Node.js using the Passport library alongside Express framework

An interesting article caught my attention on Scotch.io: https://scotch.io/tutorials/easy-node-authentication-linking-all-accounts-together Although it was published back in January 2014, Chris demonstrates how to check the value of req.user within the p ...

Navigating between two Vue2 applications

I currently have two applications, app1 and app2. App1 serves as a website at www.wxample.com with a button. My goal is to implement code in app2 that allows me to click the button on app1 and be redirected to the Login Panel in app2 for the workers module ...

Executing a for-in loop that iterates through MongoDB operations

I am facing an issue with a function that looks like this... for(key in object){ db.collection.findOne(criteria, function(err, doc){ // ... db.collection.update(...); }) }; The problem is that the value of key keeps changing befor ...

Discover the autocomplete features derived from concealed links within the webpage

Is it feasible to dynamically pass 300 or fewer strings from anchor tags on a page to jQuery's array of availableTags? var availableTags = [ "my tag", "my tag1" ]; List of Tags The server provides me with a list of tags in a specific format, limit ...

The function getElementsByTagName() returned an undefined value at index [0]

I'm delving into AJAX for the first time and encountering an error. I've seen similar issues posted by others, but none of the solutions I found seem to apply to my code. The specific problem I'm facing is that rf.getElementsByTagName("motd ...

Determine whether the numbers or values are arranged in ascending order within the input field using jQuery

I am working on a form that has n input-fields for values. The task at hand is to verify if the values are in ascending order, otherwise an error should be displayed. To streamline the process, I have incorporated a simple "cleanup" step before validation ...

Focusing on text input causes the mobile browser to reveal content beyond the limits of a div with overflow set to hidden

I am currently working on a one-page web application. The interface includes a bottom bar that slides up from off-screen, with overflow set to hidden. Within this sliding bar, there is a text input field. When tapped on mobile devices, the browser automat ...

The iPad Air 2 experiencing issues with rendering on three.js

Recently, I've transitioned to using an iPad Air 2 for work and decided to explore equirectangular panoramas. While these panoramas work perfectly on my desktop, I was excited about utilizing the device orientation features on my iPad/iPhone. However ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Error: Unable to establish connection with local host (::1) on port 50106

I am currently in the process of developing a Discord bot using Node.js and erela.js. However, I encountered an error when attempting to retrieve the server that handles erela: A node error occurred: connect ECONNREFUSED ::1:50106 2020-05-01T21:23:19.367 ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

Unable to dynamically validate the input field for the name using Angular.js

Can someone assist me with an issue I'm having? I'm encountering an error while trying to dynamically validate input fields using Angular.js. Error: TypeError: Cannot read property '$invalid' of undefined Let me explain the code t ...

What is the best way to arrange objects in an array by date using Angular 4?

My array of objects is structured like this : this.filteredData = [ {'id': 1, 'date': '04-05-2018'}, {'id': 2, 'date': '29-03-2018'}, {'id': 3, 'date': '03-04 ...

Exploring Angular scope variables using Jasmine while making an ajax request

Can anyone provide guidance on testing Angular scope variables in a controller that is created within an ajax request? Here's the setup: app.controller('NewQuestionCtrl', function ($scope, Question) { loadJsonAndSetScopeVariables($scope ...

Exploring the possibilities of using jQuery to access global variables in node.js

My issue has 3 main components. I need to declare a server-side (node.js) variable to store data for the duration of the server run, specifically just a number. I must send a number from the client (jQuery) to the server in order to update the server v ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...