Angular UI Bootstrap Datepicker: How to use date as a string and in a specific format - angularjs

What I am trying to to do is when the user selects a specific date, to be able to use that date as a string, put it as data into a JSON object and retrieve data from the database as response.
Selecting the Day I want I am getting this in the console log:
Fri Sep 04 2015 16:15:24 GMT+0300 (GTB Daylight Time)
And in order to use it I want to convert it into this:
20150904
I even used a directive but I suppose this is for a preview only.
.directive('datepickerPopup', function (){
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, controller) {
//remove the default formatter from the input directive to prevent conflict
controller.$formatters.shift();
}
}
});
Does anyone have a clue how this is going to be done?
Thank you in advance!

Try this-
This is the sample code , you can try with your code -
angular.module('frontendApp')
.controller('SearchCtrl',function ($scope, $filter) {
$scope.formattedDate = $filter('date')($scope.date_of_birth, "dd/MM/yyyy");
console.log('Formatted Date: ' + $scope.formattedDate);
});
Replace, "$scope.date_of_birth" with your ng-model.
Reference Links
http://plnkr.co/edit/akLekgX7b1rcaMg6B9rI?p=preview
https://sonnguyen.ws/angularjs-datetime-format/

You can use simple JavaScript for that and use it anywhere you feel fit(directive, filter, service etc.). Suppose 'date' contains your date. Here's the code:
var year = date.getFullYear();
var month = date.getMonth();
month = month + 1;
if(month < 10) {
month = '0' + month;
}
var day = date.getDate();
if(day < 10) {
day = '0' + day;
}
date = year.toString() + month.toString() + day.toString();
return date;

Related

AngularJs gm.datepickerMultiSelect, bad date

I am trying to use the gm.datepickerMultiSelect module in AngularJS. I have a day offset when I select a date and I have located the line that causes me problem in the library:
var dateVal = Date.parse($filter('gmISODate')(newVal)),
Can somebody help me?
More informations :
I have copy past sample from http://plnkr.co/edit/7rKzFo?p=preview
when I select a date (2016/12/20) then
newVal = "Tue Dec 20 2016 00:00:00 GMT+0100 (Paris, Madrid)"
The problem is the GMT+1 loosed when it passes through the filter
date.toISOString().split("T")[0] give me "2016-12-19"
I've found a solution
I've replace
.filter('gmISODate', function () {
return function (date) {
return date.toISOString().split("T")[0];
}
})
by
.filter('gmISODate', function () {
return function (date) {
var m = moment(date);
return m.format()
}
})
Note : moment.js library at : http://momentjs.com/

Angular Material - Datepicker

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.

Formatting and displaying date in angularjs

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;
}
};
}])

angular js custom filter does not update view or changes original array

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 !!

Paginate By Week - AngularJS

I am trying to paginate a list of events (using ng-repeat) by week in AngularJS. I have a custom filter working that only displays the events within the current week, but I am trying to add functionality to look at future and past weeks.
Here is the filter I am using for the event lists -
$scope.week = function(item) {
var weekStart = moment().startOf('week');
var weekEnd = moment().endOf('week');
var eventTime = moment(item.jsdatetime);
if (eventTime >= weekStart && eventTime <= weekEnd) return true;
return false;
};
I have tried using ng-click to call a function that uses moment.js to .add(7, 'days'); to the weekStart and weekEnd variables but can't seem to get it to work.
Any help would be appreciated.
Here's a CodePen with the basic functionality going on - http://codepen.io/drewbietron/pen/xbKNdK
The moment() always return the current date/time.
You need to store a reference to it to a variable, and then use that for manipulations.
(and since you have other variables depending on it, i would create a function that sets all those variables at once)
So in the controller i changed the top part to
var currentDate,
weekStart,
weekEnd,
shortWeekFormat = 'MMMM Do';
function setCurrentDate(aMoment){
currentDate = aMoment,
weekStart = currentDate.clone().startOf('week'),
weekEnd = currentDate.clone().endOf('week')
}
// initialize with current date
setCurrentDate(moment());
// use these methods for displaying
$scope.currentWeek = function(){ return currentDate.format(shortWeekFormat); };
$scope.currentWeekStart = function(){ return weekStart.format(shortWeekFormat); };
$scope.currentWeekEnd = function(){ return weekEnd.format(shortWeekFormat); };
Then create two methods for going to next/previous week
$scope.nextWeek = function(){
setCurrentDate(currentDate.add(7,'days'));
};
$scope.prevWeek = function(){
setCurrentDate(currentDate.subtract(7,'days'));
};
(moment.js implements valueOf so you do direct comparisons)
And finally change your week filter to actually compare the dates (using .isSame(), .isBefore() and .isAfter()) instead of the moment objects (which was wrong as you cannot do direct comparisons on custom objects)
$scope.week = function(item) {
var eventTime = moment(item.jsdatetime);
if ((eventTime.isSame(weekStart) || eventTime.isAfter(weekStart))&&
(eventTime.isSame(weekEnd) || eventTime.isBefore(weekEnd))) return true;
return false;
};
$scope.week = function(item) {
var eventTime = moment(item.jsdatetime);
return (eventTime >= weekStart && eventTime <= weekEnd);
};
(you also, most likely, want the ng-repeat on the li elements and not the ul)
Demo at http://codepen.io/gpetrioli/pen/QwLRQB
The weekStart and weekEnd variables don't exist outside of the scope of week(item). If you're using ngClick to call a function that tries to modify those variables, it'll just return undefined. I don't know how your layout is but I would pull those two variables outside of the week function and make them $scope variables.
Additionally, I would have ngClick call a function that would change the two $scope variables (either adds 7 or subtracts 7 depending on which direction you want to go in).
$scope.weekStart = moment().startOf('week');
$scope.weekEnd = moment().endOf('week');
$scope.week = function(item) {
var eventTime = moment(item.jsdatetime);
if (eventTime >= $scope.weekStart && eventTime <= $scope.weekEnd) return true;
return false;
};
$scope.update= function(direction) {
$scope.weekStart.add(direction, 'days');
$scope.weekEnd.add(direction, 'days');
}
And create two buttons in your view:
Previous week
Next week

Resources