Format Date to Year - angularjs

I've got a date coming in from an API that returns the date like this: 2012-10-12 00:00:00
I'm printing it to my page like this:
<span class="year" ng-bind-html="hit._highlightResult.original_release_date.value"></span>
with original_release_date.value being that date (2012-10-12 00:00:00). Does anyone know a quick and easy way to just return the year?
Any help is appreciated. Thanks in advance!

you can use the date api in angularjs
<span class="year"> {{ hit._highlightResult.original_release_date.value | date:"yyyy" }} </span>
hit._highlightResult.original_release_date.value should be a (according to doc)
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.
so create javascript date object and format it to show only the year,
step 1 - create a filter to get a date object from a string (2012-10-12 00:00:00)
app.filter('dateToISO', function() {
return function(input) {
var dateTime = input.split(" ");
var date = dateTime[0];
var datePartials = date.split("-");
var time = dateTime[1];
var timePartials = time.split(":");
var formattedDate = new Date();
formattedDate.setFullYear(datePartials[0]);
formattedDate.setMonth(datePartials[1]-1);
formattedDate.setDate(datePartials[2]);
formattedDate.setHours(timePartials[0]);
formattedDate.setMinutes(timePartials[1]);
return formattedDate;
};
});
step 2 - create a controller function to get the date object
$scope.getDate = function() {
return $filter('dateToISO')('2012-10-12 00:00:00');
};
step 3 - call that function and get the date object to format in the HTML
<span class="year"> {{ getDate() | date:"yyyy" }} </span>
here is the working Demo Plunker

This may be a bit off and cheating but I think '2012-10-12 00:00:00'.split('-')[0] will do the trick

Related

Angular date filter converter, but date is always converted to UTC

My filter:
.filter('emedicineDateTimeFormat', function ($filter) {
return function (input) {
if (input == null) { return ""; }
var date = $filter('date')(new Date(input), 'dd.MM.yyyy hh:mm:ss');
return date.toUpperCase();
};
});
if Input is: 2017-01-04T14:30:00
then output is 04.01.2017 03:15:00
and not 04.01.2017 14:15:00
Why?
If you want get 24-hours time use upper-cased H. An example is here.
'dd.MM.yyyy HH:mm:ss'
Are you sure that you didn't misspell in output and expected result?
Do you live in UTC+01:00 timezone?
By default AngularJS uses browser timezone. If you want use UTC you should pass the 3rd argument to date filter 'UTC'. Look here.

Angularjs: how to change the date format

I am getting date in loop from database. The format is like "2015-09-21 18:30:00". But I want to change it as 'dd/MM/yyyy'.
I tried like this
{{obj.added_date | date : 'dd/MM/yyyy'}}
It shows like
2015-09-21 18:30:00 | date : 'dd/MM/yyyy'}}
If I use fulldate is shows me like:
2015-09-21 18:30:00 | date : 'fullDate'}}
for shortDate it shows like this:
2015-09-21 18:30:00 | date : 'shortDate'}}
The date your passing to view is actually a string and hence angular date filter does not recognise it as date object. You need to convert it to date object first.
Also be careful with firefox, it doesn't work for new Date(); if date separator in '-' instead '/'. So I would also suggest below
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope','$filter', function ($scope,$filter) {
var dateStr = '2015-09-21 18:30:00';
$scope.dt = $filter('date')(new Date(dateStr.split('-').join('/')), "d/M/yyyy 'at' h:mm a");
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<bod ng-app="myApp">
<div ng-controller="MyCtrl">
<div>{{dt}}</div>
</div>
</body>
EDIT: I have created a filter which will work for converting string to date object and will work in loop too
var myApp = angular.module('myApp',[]);
myApp.controller("MyCtrl", function ($scope) {
$scope.dt = '2015-09-21 18:30:00';
});
myApp.filter('formatDate', function(dateFilter) {
var formattedDate = '';
return function(dt) {
console.log(new Date(dt.split('-').join('/')));
formattedDate = dateFilter(new Date(dt.split('-').join('/')), 'd/M/yyyy');
return formattedDate;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<bod ng-app="myApp">
<div ng-controller="MyCtrl">
<div>{{dt | formatDate: dt:'d/M/yyyy'}}</div>
</div>
</body>
Hope this helps
The date format that you have specified doesn't match the input specifications provided in the AngularJS documentation. The following is taken from https://docs.angularjs.org/api/ng/filter/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.
I would suggest that you convert the date value into milliseconds and then pass it into the filter.
What i have done is before bindind the data in angular JS you can format the data
//Here i am taking the DOB from session and converted the format in dd-MM-yyyy format
string DOB = ((ABC.Models.Student)Session["Student"]).DOB.ToString("dd-MM-yyyy");
//Here i have used a hidden field where i am going to store DOB in ng-Init
<input type="hidden" name="DOB" id="DOB" ng_init = "DOB=' " + "Date of Birth: " + DOB + "'" /><br />
Later can call your ng-bind method for displaying.
<p ng-bind="DOB"></p>

Format time in Angular

I have a time field coming from the database that is formated like "14:37:39". I need it formated to be like "2:37 PM". I have tried to use the date filter (which formats time as well), but with no luck.
Help!
<span class="time">{{ feeding.time | date: "shortTime" }}</span>
You can build your own filter based on the format you're expecting...
angular.module('foo', [])
.filter('formatTime', function ($filter) {
return function (time) {
var parts = time.split(':');
var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
return $filter('date')(date, 'h:mm a');
};
});
{{ '14:37:39' | formatTime }}
Outputs 2:37 PM
Live Demo
I think that your problem is that feeding.time is a string and the date filter is expecting a date.

Set an AngularJS date filter format to be used by all references to the date filter?

Rather that having to define a custom format for each call to the date filter, is there a way to globally define a default format (other than 'medium')?
I would like to have the format set in one file rather than all over the place in my code (the date format may end up being changed in the future and a modification in one file would be much nicer than having to make changes in many files).
This is what I am doing now (defining date format each time):
{{systemTime | date:'dd MMMM # HH:mm:ss'}}
{{modifiedTime | date:'dd MMMM # HH:mm:ss'}}
{{getShippedTime() | date:'dd MMMM # HH:mm:ss'}}
etc.
I was thinking of creating a custom filter (let's call it myDate), which would act as a wrapper and then pass off the date string to the Angular date filter with my custom format, so then my code could just look like this:
{{systemTime | myDate}}
{{modifiedTime | myDate}}
{{getShippedTime() | myDate}}
etc.
However, I can't figure out how to make the myDate filter point to the Angular date filter.
Thanks for your help.
Based on some more research and then considering the comment by moderndegree, I have found that the following myDate filter will work:
.filter('myDate', function($filter) {
var angularDateFilter = $filter('date');
return function(theDate) {
return angularDateFilter(theDate, 'dd MMMM # HH:mm:ss');
}
});
Try this
angular.module('yourmodule').filter('myDate', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input), 'dd MMMM # HH:mm:ss');
return _date.toUpperCase();
};
});
Html
{{systemTime | myDate}}
Date filtering and formatting in Angular js.
Use a decorator,
It's not what you explicitly asked for, use a decorator. it's built in angular and designed to patch services, directives, filters etc ...
in your case, if the date filter is not provided, you should use your custom date format.
app.config(function ($provide) {
$provide.decorator('dateFilter', function ($delegate) {
return function () {
// Check if the date format argument is not provided
if (!arguments[1]) {
arguments[1] = 'dd MMMM # HH:mm:ss';
}
var value = $delegate.apply(null, arguments);
return value;
};
})
});
The format defaults to mediumDate if none is provided. There is nothing built in to have it default to something else.
https://github.com/angular/angular.js/blob/master/src/ng/filter/filters.js#L382
In case you are working with .aspx pages and have the date format stored in a configuration file...
From the .aspx that injects your Angular page, set a global variable with the web.config date format
var _settingsDateFormat = '<%=appSettings.DateFormat%>';
Set a global filter to be used through your app
yourModule.filter('myDateFormat', function ($filter) {
return function (input) {
if (input == null) { return ""; }
var formattedDate = $filter('date')(new Date(input), _settingsDateFormat);
return formattedDate;
};
});
Just add the custom filter to your dates
Effective {{row.StartDate|myDateFormat}} - {{row.StopDate|myDateFormat}}

angularjs date filter not formatting my json value

I have a service that returns json like so:
"Results":[{"Id":"1","SomeDate":"2/19/2013 10:34:04 PM"}
When i try to format using binding, it doesnt work - it just displays the string above:
{{values.SomeDate| date:'mediumTime' }}
However, it works if i just pass in this format:
{{ '1997-03-01T00:00:00+01:00' | date:'mediumTime'}}
What is the best way to fix this?
As mentioned in the comments by charlietfl, a clean option would be to update the service to return a date format already compatible with the built-in angular filters.
However, if this is not possible, you could set up a custom filter to parse your dates.
A (very small) library that I recommend is Moment.js:
http://momentjs.com/
The following is an example blog post on how to wrap Moment.js in a custom angular filter:
http://www.34m0.com/2012/07/angularjs-user-friendly-date-display.html
angular.module('myModule').
filter('fromNow', function() {
return function(dateString) {
return moment(new Date(dateString)).fromNow()
};
});
This would be used like:
{{ reply.createdDate | fromNow }}
You can place this in your controller:
$scope.toJsDate = function(str){
if(!str)return null;
return new Date(str);
}
and then:
{{toJsDate(values.SomeDate)| date:'mediumTime' }}
I would second #AlexOsborn's suggestion to use moment.js to create a custom filter because moment.js can parse the string containing the date. In my implementation of the filter, I also delegate date formatting to moment.js because I feel moment.js' date formatting feature is more comprehensive than angular.js':
angular
.module("YourModuleNameHere")
.filter("formatdate", [function () {
var result = function (date, formatstring) {
if(formatstring === null) {
formatstring = "DD MMM YYYY";
}
return moment(date).format(formatstring);
}
return result;
}]);
And you use it just like you'd use angular.js date filter (but to format the date you'd use moment.js formatting codes):
<p>Today is {{moment() | formatdate}}</p>
<p>Another date: {{values.SomeDate | formatdate:"ddd D MMM YYYY"}}</p>

Resources