Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  184] [ 6]  / answers: 1 / hits: 31404  / 8 Years ago, mon, april 25, 2016, 12:00:00

I am struggling with some datetime formating in angularJS.



I would like to obtain the following date format 25/11/1990 14:35
based on a datetime string containing 1990-11-25 14:35:00 without having to create a Date object in the controller.



It seems like angular can only achieve proper datetime formatting if the input is a Date object or if the String does not contain hours or 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/



According to angular's documentation on the date filter,
the only format allowed for datetime string are:




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 so a way to format a string containing 1990-11-25 14:35:00 into 25/11/1990 14:35 directly in the html without having to create a Date object ?



Thanks for your help !


More From » angularjs

 Answers
28

It seems like angular can only achieve proper datetime formatting if the input is a Date object or if the String does not contain hours or minutes



If you want your string recognized as a date you should use the date formatted according to the ISO8601 standard. So 1990-11-25 14:35:00 becomes 1990-11-25T14:35:00Z, you can also include the offset if you want (its in the spec). You can then use the existing date filter built into Angular.


From the date filter documentation on param date



Date to format either as Date object, milliseconds (string or number) or various ISO 8601 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). If no timezone is specified in the string input, the time is considered to be in the local timezone.



Code update


<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";
}

Updated JsFiddle


[#62405] Friday, April 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;