Format Date time in AngularJS
Asked Answered
N

13

125

How do I properly display the date and time in AngularJS?

The output below shows both the input and the output, with and without the AngularJS date filter:

In: {{v.Dt}}  
AngularJS: {{v.Dt | date:'yyyy-MM-dd HH:mm:ss Z'}}

This prints:

In: 2012-10-16T17:57:28.556094Z 
AngularJS: 2012-10-16T17:57:28.556094Z

The desired display format is 2010-10-28 23:40:23 0400 or 2010-10-28 23:40:23 EST

Narial answered 16/10, 2012 at 18:13 Comment(0)
R
63

v.Dt is likely not a Date() object.

See http://jsfiddle.net/southerd/xG2t8/

but in your controller:

scope.v.Dt = Date.parse(scope.v.Dt);
Ribbonwood answered 16/10, 2012 at 18:27 Comment(1)
David in my case date is stored in DD/MM/YYYY format in Database. I convert that i show it user DD.MM.YYYY format in textbox or take user input in that format and same gets updated in my model. how to change that before passing it to DB. how should i changeTownship
E
123

Your code should work as you have it see this fiddle.

You'll have to make sure your v.Dt is a proper Date object for it to work though.

{{dt | date:'yyyy-MM-dd HH:mm:ss Z'}}

or if dateFormat is defined in scope as dateFormat = 'yyyy-MM-dd HH:mm:ss Z':

{{dt | date:dateFormat }}
Electro answered 16/10, 2012 at 18:20 Comment(4)
As the format is a cosmetic option it is generally a better idea to do this directly on the view.Hecklau
thnkx..super ans. is it possible to show time in 12 hour format ?Chanel
dt can be an unix timestamp in integer format works tooTrinary
it is not required to be a Date type for variable. Timestamp long works good tooEmotionality
R
63

v.Dt is likely not a Date() object.

See http://jsfiddle.net/southerd/xG2t8/

but in your controller:

scope.v.Dt = Date.parse(scope.v.Dt);
Ribbonwood answered 16/10, 2012 at 18:27 Comment(1)
David in my case date is stored in DD/MM/YYYY format in Database. I convert that i show it user DD.MM.YYYY format in textbox or take user input in that format and same gets updated in my model. how to change that before passing it to DB. how should i changeTownship
B
60

I know this is an old item, but thought I'd throw in another option to consider.

As the original string doesn't include the "T" demarker, the default implementation in Angular doesn't recognize it as a date. You can force it using new Date, but that is a bit of a pain on an array. Since you can pipe filters together, you might be able to use a filter to convert your input to a date and then apply the date: filter on the converted date. Create a new custom filter as follows:

app
.filter("asDate", function () {
    return function (input) {
        return new Date(input);
    }
});

Then in your markup, you can pipe the filters together:

{{item.myDateTimeString | asDate | date:'shortDate'}}
Beckman answered 5/5, 2014 at 18:32 Comment(1)
Yeah, more reliable and efficient.. Thanks for sharingNothingness
S
56

you can get the 'date' filter like this:

var today = $filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss Z');

This will give you today's date in format you want.

Sagittarius answered 11/4, 2014 at 16:44 Comment(1)
lol yes, Leandro. I don't know how it got it like that. I think I was thinking 'use'.Sagittarius
P
49

Here is a filter that will take a date string OR javascript Date() object. It uses Moment.js and can apply any Moment.js transform function, such as the popular 'fromNow'

angular.module('myModule').filter('moment', function () {
  return function (input, momentFn /*, param1, param2, ...param n */) {
    var args = Array.prototype.slice.call(arguments, 2),
        momentObj = moment(input);
    return momentObj[momentFn].apply(momentObj, args);
  };
});

So...

{{ anyDateObjectOrString | moment: 'format': 'MMM DD, YYYY' }}

would display Nov 11, 2014

{{ anyDateObjectOrString | moment: 'fromNow' }}

would display 10 minutes ago

If you need to call multiple moment functions, you can chain them. This converts to UTC and then formats...

{{ someDate | moment: 'utc' | moment: 'format': 'MMM DD, YYYY' }}

https://gist.github.com/cmmartin/341b017194bac09ffa1a

Pelfrey answered 11/11, 2014 at 5:16 Comment(1)
This is brilliant and can also be combined with Moment Timezone. e.g.: {{foo.created_at | moment: 'tz': 'America/New_York' | moment: 'format': 'h:mm a z'}}Mehitable
B
23

Here are a few popular examples:

<div>{{myDate | date:'M/d/yyyy'}}</div> 7/4/2014

<div>{{myDate | date:'yyyy-MM-dd'}}</div> 2014-07-04

<div>{{myDate | date:'M/d/yyyy HH:mm:ss'}}</div> 7/4/2014 12:01:59

Bruner answered 29/4, 2015 at 12:26 Comment(1)
simple, elegant and exactly what was askedFletcherfletcherism
A
15

Have you seen the Writing directives (short version) section of the documentation?

HTML

<div ng-controller="Ctrl2">
      Date format: <input ng-model="format"> <hr/>
      Current time is: <span my-current-time="format"></span>
</div> 

JS

function Ctrl2($scope) {
  $scope.format = 'M/d/yy h:mm:ss a';
}
Anastasia answered 16/10, 2012 at 18:19 Comment(1)
I think your comment is very valid. Learning to do filters is an essential part of AngularJS. It's really not that difficult.Walloping
A
6

Inside a controller the format can be filtered by injecting $filter.

var date = $filter('date')(new Date(),'MMM dd, yyyy');
Aide answered 5/6, 2015 at 3:25 Comment(0)
A
5

Simplly if you want to output like "Jan 30, 2017 4:31:20 PM" then follow to simple step

step1- Declare following variable in js controller

$scope.current_time = new Date();

step2- display in html page like

{{current_time | date:'medium'}}

Antherozoid answered 30/1, 2017 at 11:5 Comment(0)
M
5

we can format the date on view side in angular is very easy....please check the below example:

{{dt | date : "dd-MM-yyyy"}}

Mccary answered 17/4, 2017 at 7:20 Comment(0)
S
3

You can use momentjs to implement date-time filter in angularjs. For example:

angular.module('myApp')
 .filter('formatDateTime', function ($filter) {
    return function (date, format) {
        if (date) {
            return moment(Number(date)).format(format || "DD/MM/YYYY h:mm A");
        }
        else
            return "";
    };
});

Where date is in time stamp format.

Semasiology answered 28/7, 2015 at 5:21 Comment(0)
U
1

Add $filter dependency in controller.

var formatted_datetime = $filter('date')(variable_Containing_time,'yyyy-MM-dd HH:mm:ss Z')
Uriisa answered 22/11, 2016 at 9:44 Comment(1)
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!Monosaccharide
V
0

I would suggest you to use moment.js it has got a good support for date formatting according to locales.

create a filter that internally uses moment.js method for formatting date.

Viviyan answered 11/1, 2017 at 3:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.