I created a datepicker directive which uses a jquery datepicker to generate calender.We can format the way it displays the data after selecting a date. I have some date which is stored in the database.
My requirement is to load the date in some specific format only when it displaying and don't want to change the model data.
I created a filter to format the text but it often returns "Nan Undefined NaN"
This is my filter
myUploadApp.filter('cmdate', ['$filter', function ($filter) {
return function (input, format) {
if (input) {
return $filter('date')(new Date(Date.parse(input)), format);
} else {
return null;
}
};
}]);
And to invoke this filter " cmdate :'dd MMM yyyy' " this is added.My input date format will be like this "23/04/2016".
You should checkout moment.js - http://momentjs.com/
I use it to turn dates like this "2016-05-12T14:00:00.346Z" to words like "in 10 hours"
fromNow.filter.js:
myapp.filter('fromNow', [, function () {
return function (date) {
return moment(date).fromNow();
}
};
}]);
Check out to see if it has the formatter you require
Date.parse accepts string format MM/dd/yyyy, and your input likes dd/MM/yyyy, That's why it does not worked.
If you insist to use this format, need to correct the format before parse;
.filter('cmdate', ['$filter', function ($filter) {
return function (input, format) {
//swap month and date first
input = input.split('/');
input[0] = input.splice(1, 1, input[0])[0];
input = input.join('/');
var date = new Date(Date.parse(input));
if (input) {
return $filter('date')(new Date(Date.parse(input)), format);
} else {
return null;
}
};
}])
Related
I have the following files.
index.js
...
completedTooltip = 'Completed on 2019-02-02T23:59:59-07:00';
...
index.html
...
{{completedTooltip | date : 'MM/dd/yyyy'}}
...
The date doesn't get formatted here and just spits out the string.
Is there any way I can make this work OR do I have to just have 2 separate vars so that one var can hold the text and the other can hold the date?
You can create custom filter,
app.filter("anyName", function($filter) {
return function(input, format) {
var txtArr = input.split(' ');
txtArr[2] = $filter('date')(txtArr[2], format);
return txtArr.join(' ');
};
});
And use that in your HTML
{{completedTooltip | anyName : 'MM/dd/yyyy'}}
I got a wired error
I have directive date picker
I have watch listener while the date change
$scope.$watch('model', function (newDate) {
if (newDate) {
if ($scope.hideDay) {
$scope.dateFields.day = 1;
} else {
$scope.dateFields.day = new Date(newDate).getUTCDate();
}
$scope.dateFields.month = new Date(newDate).getUTCMonth() +1;
$scope.dateFields.year = new Date(newDate).getUTCFullYear();
} else {
if ($scope.hideDay) {
$scope.dateFields.day = 1;
} else {
$scope.dateFields.day = null;
}
$scope.dateFields.month = null;
$scope.dateFields.year = null;
}
});
My weird problem is that I have a search box
<input class="free-txt" ng-model="search.name" placeholder="Free search" />
When I typed in the search box The watch model changed with no reason.
What can be the reason for this bug and how can I fixed it?
Here is the full demo
https://embed.plnkr.co/yGqE33kZNwGz7NaNDOD5/
Select day
Select Month
Open the Year modal than Write in the free text "78"
Select The year
The bug when Typing in the free text the day and month change to null
by default angular $watch watch object by reference
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
objectEquality:
Compare for object equality using angular.equals instead of comparing for reference equality.
(default: false)
try to add a parametre to true for watching object or use watchcollection and give it the variables you need
$scope.$watch('model', function (newDate) {
...
},true );
the directive update the model only when the date is valid :
$scope.checkDate = function () {
$timeout(function () {
var date = rsmDateUtils.checkDate($scope.dateFields);
if (date) {
// the watch is called what date is valid with a year
if ($scope.hideDay) {
$scope.model = $filter('date')(date, 'yyyy-MM');
} else {
$scope.model = $filter('date')(date, 'yyyy-MM-dd');
}
}
});
};
how to display Json datetime formate in angularJs its showing Datetime as"/Date(820434600000)/"
Angular Code
app.controller("MyDeptCntrl", function ($scope, MyDeptSer) {
$scope.BtnDept = function () {
var Dept = MyDeptSer.GetDeptData();
Dept.then(function (d) {
$scope.DeptData = d.data;
// $filter('date')(date, format, timezone)
},function(e){
alert('Loading Failed....')
})
}
use below function to parse the date first
function dateParser(input){
input = input.replace('/Date(', '');
return new Date(parseInt(input,10));
}
so
$scope.DeptData = dateParser(d.data);
You can try this
convertJsonDateTimeToJs: function (jsonDate) {
var dateSlice = jsonDate.slice(6, 24);
var milliseconds = parseInt(dateSlice);
return new Date(milliseconds);
}
I'd recommend changing your server side code to use a friendlier JSON serializer but if not, try:
// You start with /Date(820434600000)/
// substr(6) takes off the /Date( part and pass the number 820434600000 into the parseInt function.
// Note: the parseInt function will ignore the )/ and the end.
var friendlyDate = new Date(parseInt($scope.DeptData.someDateMember.substr(6)));
// Then, you can format it using angular date filter -- for example:
$scope.formattedDate = $filter('date')(friendlyDate, 'MM/dd/yyyy');
Can anyone explain why the Datepicker expects value to be date object as per the official example?
https://material.angularjs.org/latest/demo/datepicker
To be honest this is a pain because before binding server response to the form I have to determine if a field is data type and convert the value:
$scope.myDate = new Date('2015-01-11');
Is there any way I could simply populate datepicker with a string value?
$scope.myDate = '2015-01-11';
The problem with a string value would be parsing. May 10, 2016 and October 5, 2016 could be confused. 2016-05-10 or 2016-10-05. The date object protects against that. Can you not use a defined filter to convert your string data to a date object?
I quickly modified some code below from a Date Filter I have for Angular 1.x, which uses a numeric date format of YYYYMMDD (20160516).
/**
* #name yourDate
* #ngdoc filter
* #requires $filter
* #param DateValue {string} Date Value (YYYY-MM-DD)
* #returns Date Filter with the Date Object
* #description
* Convert date from the format YYYY-MM-DD to the proper date object for future use by other objects/filters
*/
angular.module('myApp').filter('yourDate', function($filter) {
var DateFilter = $filter('date');
return function(DateValue) {
var Input = "";
var ResultData = DateValue;
if ( ! ( (DateValue === null) || ( typeof DateValue == 'undefined') ) ) {
if ( Input.length == 10) {
var Year = parseInt(Input.substr(0,4));
var Month = parseInt(Input.substr(5,2)) - 1;
var Day = parseInt(Input.substr(8, 2));
var DateObject = new Date(Year, Month, Day);
ResultData = DateFilter(DateObject); // Return Input to the original filter (date)
} else {
}
} else {
}
return ResultData;
};
}
);
/**
* #description
* Work with dates to convert from and to the YYYY-MM-DD format that is stored in the system.
*/
angular.module('myApp').directive('yourDate',
function($filter) {
return {
restrict: 'A',
require: '^ngModel',
link: function($scope, element, attrs, ngModelControl) {
var slsDateFilter = $filter('yourDate');
ngModelControl.$formatters.push(function(value) {
return slsDateFilter(value);
});
ngModelControl.$parsers.push(function(value) {
var DateObject = new Date(value); // Convert from Date to YYYY-MM-DD
return DateObject.getFullYear().toString() + '-' + DateObject.getMonth().toString() + '-' + DateObject.getDate().toString();
});
}
};
}
);
This code just uses the standard Angular Filter options, so you should then be able to combine this with your Material date picker.
I have created a custom filter to filter images that i get from MySql using php.
Then i pass the array into angular using encode and what i get is $scope.pics which has ID,pic_name and upload_date for each entry.
The custom filter works well as i can see it in the console . The problem is i am confused regarding how and where to call the filter .
I need to send the date range(that gets updated in the directive)into the filter
.
my directive :
app.directive('datepicker', function(){
return {
require: 'ngModel',
link : function(scope,element,attrs, ngModel){
element.datepicker({
dateFormat:'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1950:2015',
yearRange: "-100:+0",
onSelect: function(dateText) {
scope.$apply(function() {
ngModel.$setViewValue(dateText);
scope.helloFilter(scope.from,scope.to);//calling filter function- defined in controller ,also from and to are my ng-models in my view for the two dates
});
},
});
}
}});
my controller:
app.controller('MyController',function($scope,$http,$filter) {
.......
$scope.helloFilter = function(from,to){
return $filter('dateFilter')($scope.pics,from,to);
};
my view: (its messy but i need help with just the date filter part !)
<div ng-repeat="pic in pics|filter:{pic_name:n}|filter : dateFilter ">
my filter:
app.filter('dateFilter', function(){
return function(arr,from,to) {
var a =[];// to store upload dates from the recieved array 'arr'
var arrNew = [];//array to store original array
var picFilter = [];// to store filered array
var i = 0;
for(i=0;i<arr.length;i++){
arrNew[i] = arr[i];//initialising to original array
}
if(from == null){ // if user doesnt provide start date
from = moment("01011970","DD MM YYYY").format('MM DD YYYY');
}
f = moment((from),'DD MM YYYY').format('YYYY/MM/DD');//format input date to compare with MySql date
t = moment((to),'DD MM YYYY').format('YYYY/MM/DD');
var cnt=0;// to enter filtered data into array to be returned
for(i=0;i<arr.length;i++){
a[i] = arr[i].upload_date;//extracting date to compare
con1 = moment(a[i],'YYYY MM DD').isAfter(f);
con2 = moment(a[i],'YYYY MM DD').isBefore(t);
if(con1 && con2){// if the dates in database lie between the range
picFilter[cnt] = arr[i];//store the filtered array
cnt++;
}
}
if (picFilter.length>0){
arrNew.length=0;
for(i=0;i<picFilter.length;i++){
arrNew[i] = picFilter[i];//store filtered array
}
} return arrNew;
}
});`
The problem is :
The console shows the filter has worked perfectly .My issues :
1. Am i applying the date filter correctly?? (The 1st filter for pic_name works properly)
2.I dont know what happens to my returned array ? How do i get it reflected in my view?
3. If instead of
$scope.helloFilter = function(from,to){
return $filter('dateFilter')($scope.pics,from,to);
};
I write :
$scope.helloFilter = function(from,to){
$scope.pics = $filter('dateFilter')($scope.pics,from,to);
};
My original array gets modified.
My model updates are not updated in the view. I also tried using return true.Then used $scope.$apply(),also $timeout !! none of them seem to work .
I am new to angularjs and I have a number of doubts related to its basics:-( Pls help !!