Formatting a datetime string in Angular to display as yyyy-MM-dd HH:mm

I'm facing an issue with datetime formatting in angularJS.

I'm trying to convert the datetime "1990-11-25 14:35:00" into the format 25/11/1990 14:35, without using a Date object in the controller.

It seems like angular can only handle proper datetime formatting if the input is a Date object or lacks hours and minutes.

index.html

<div ng-app ng-controller="Ctrl">
   String: {{'1990-11-25 14:35:00' | date:"dd/MM/yyyy HH:mm"}}<br>
   string date: {{'1990-11-25' | date:"dd/MM/yyyy"}}<br>
   Date: {{myDate | date:"dd/MM/yyyy HH:mm"}}
</div>

controller.js

function Ctrl($scope)
{
    $scope.myDate = new Date("1990-11-25 14:35:00");
}

Output

string: 1990-11-25 14:35:00 
string date: 25/11/1990 
date: 25/11/1990 14:35

http://jsfiddle.net/CkBWL/612/

As per angular's date filter documentation, only certain datetime string formats are supported.

datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ)

Is there a way to directly format a string like "1990-11-25 14:35:00" into 25/11/1990 14:35 in the HTML without involving a Date object?

Thank you for your assistance!

Answer №1

It appears that in order for angular to correctly format datetime, the input must either be a Date object or not include hours and minutes.

If you want Angular to recognize your string as a date, it should follow the ISO 8601 standard. For example, convert 1990-11-25 14:35:00 to 1990-11-25T14:35:00Z and consider including the offset (as specified). The built-in date filter in Angular can then be utilized.

Referencing the date filter documentation on parameter date

The date to be formatted should be provided as either a Date object, milliseconds (string or number), or various ISO 8601 datetime string formats (e.g., yyyy-MM-ddTHH:mm:ss.sssZ and its variants). Time is assumed to be in the local timezone if no timezone is specified in the input string.

Code revision

<div ng-app ng-controller="Ctrl">
    String: {{'1990-11-25T14:35:00Z' | date:"dd/MM/yyyy HH:mm"}}
    <br>
    Date: {{date | date:"dd/MM/yyyy HH:mm"}}
</div>

function Ctrl($scope) {
    $scope.date = "1990-11-25T14:35:00Z";
}

Revised JsFiddle

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

conditional statement for manipulating data in javascript/html

I am working on appending results in an object as options in a datalist dropdown. While it is functioning correctly, the issue arises when not all elements have a specific level in the object consistently, impacting which results are added to the list. $( ...

Issue with AngularJs app in IE11: Error message "Object does not have 'then' method"

Encountering an error in IE that says: "TypeError: Object doesn't support property or method 'then'", while trying to execute the following function within my AngularJs controller: GetUserAccessService.checkForValidHashPeriod() .then(fu ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

What is the best way to utilize a REST API in AngularJS that will provide a

I have a REST API that returns either true or false. I tested the API in Postman and it successfully returns the expected values. Now, I need to integrate this service into an AngularJS application. However, when calling the service in AngularJS, it curr ...

invoking a PHP function within a JavaScript script

In my collection of essential functions, there is one that I am particularly interested in: //the functions file //........ function user_exists($username){ $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') F ...

The filter function in JavaScript's Array is malfunctioning on Internet Explorer version 7

My web application includes a jQuery plugin that is functioning correctly in Internet Explorer 10 and 11. However, it is not working in IE 7. Upon investigation, I discovered that the value of the filter method is showing as undefined. The line of code th ...

I am facing an issue with Recharts not occupying the full width in my Nextjs/Reactjs project. Despite setting it to 100% width, it does not behave as

I am currently working with Recharts in combination with Next.js and Tailwindcss. I decided to create my own barchart by copying a code snippet from Recharts, but encountered an issue where changing the height to aspect worked fine, however setting the wid ...

Ionic app on mobile device experiencing issue with Autocomplete feature not filtering correctly in Angular

I am facing an issue with my autocomplete form. It works perfectly fine locally, but once compiled to a PWA, the data filtering feature stops functioning properly. The API is returning a JSON array response as expected. var modify = function (term) ...

Issues with the Lengthmenu option in Bootstrap Datatables Javascript

I'm currently facing an issue with my bootstrap datatables searchable table. Everything is working fine, except for the fact that users are unable to choose how many rows they want to see per page. The default setting of 10 results per page is not suf ...

I am looking for a unique array that is distinct and can be used in a reusable function

I'm struggling to create a unique array using this function. ---Here is the Function I'm Working With--- var Array = [2, 0, 1, 9, 1, 3, 2, 4, 5, 5, 3, 4] function uniqueArrayValues(val){ var newArray=[]; for(var i=0 ; i < val.length ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

Connecting Angular components to the Document Object Model (DOM)

In previous versions of AngularJS, you could create a directive and link it to an existing controller, allowing you to use the same controller for multiple directives with different templates. angular .module('App') .component('Name', ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Tips for eliminating duplicate words and potentially incorporating new terms into a text

Is there a way to eliminate specific words that are repeated exactly twice in a string, and if possible, add the word "and"? This should only apply to certain characters. For instance, take the following example: "Intruction in seated LE AROM x10 each ins ...

Starting a new React project

prtScn I'm encountering an issue while trying to initiate a new react app in Visual Studio Code. I have been following the given instructions as follows: in the visual code terminal : create-react-app sali (sali is the name) npm install node node_m ...

How can NodeJS implement ThreadLocal variable functionality without relying on req and res.locals?

In a specific situation, I am required to handle business logic and logging for each request separately. This means that the data stored should not overlap with data from other requests. Using res.locals or req objects is not an option in this case becaus ...

Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this: angular.module( 'example', [] ).directive( ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Issue with sending data via $http.post request

Is there an issue with my approach? I am not getting any post variables in /url when I try the following: $http.post("/url", { something: "something" }) .success(function(data) { console.log(data); }).error(function(data){ alert("An erro ...