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.
Related
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');
When using the md-datepicker directive in angular material, the date format doesn't seem to work for direct input.
If I select a date in the calendar, it will be displayed as specified (in my case DD-MM-YYYY) but if I try to change the input manually, my entry is analysed as MM-DD-YYYY.
So far, my datepicker is set using this code from this question
angular.module('MyApp').config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD-MM-YYYY') : '';
};
});
Here is a codepen to see the problem in action.
Is there a way to setup the entry format?
Format date event is not enough. You should also configure parse date event.
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD-MM-YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
See updated pen: http://codepen.io/anon/pen/GpBpwZ?editors=101
The complete solution base it's:
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD-MM-YYYY') : '';
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD-MM-YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
config($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
if(date !== null) {
if(date.getMonthName == undefined) {
date.getMonthName = function() {
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
return monthNames[this.getMonth()];
}
}
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + ' ' + date.getMonthName() + ' ' + year;
}
};
}
Two more definitions need to provide apart from formatDate -
parseDate - this to make sure manually entered date is valid
isDateComplete - this to make sure not to start validating partially entering date
Reference
/**
* #param date {Date}
* #returns {string} string representation of the provided date
*/
$mdDateLocaleProvider.formatDate = function (date) {
return date ? moment(date).format('DD-MM-YYYY') : '';
};
/**
* #param dateString {string} string that can be converted to a Date
* #returns {Date} JavaScript Date object created from the provided dateString
*/
$mdDateLocaleProvider.parseDate = function (dateString) {
var m = moment(dateString, 'DD-MM-YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
/**
* Check if the date string is complete enough to parse. This avoids calls to parseDate
* when the user has only typed in the first digit or two of the date.
* Allow only a day and month to be specified.
* #param dateString {string} date string to evaluate for parsing
* #returns {boolean} true if the date string is complete enough to be parsed
*/
$mdDateLocaleProvider.isDateComplete = function (dateString) {
dateString = dateString.trim();
// Look for two chunks of content (either numbers or text) separated by delimiters.
var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ .,]+|[/-]))([a-zA-Z]{3,}|[0-9]{1,4})/;
return re.test(dateString);
};
I Want to filter event by date but date is pass by normal input type="text" not kendo default datepicker.And display passing date in kendo schduler header But cant not change view date.This is my code.........
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler.view().startDate(item.StartDate);
scheduler.view().endDate(item.EndDate);
scheduler.view(("day"));
$scope.scheduler.dataSource.read();
};
This is my filter param
parameterMap: function (options, operation) {
var popupheight = $(window).height() - 180 + 'px';
$scope.popupWraperForTryout = popupheight;
var scheduler = $("#scheduler").data("kendoScheduler");
if (searchCount != 0) {
if (operation === "read") {
return {
filterByPersonalEvent: $scope._filterParamObj.filterBypersonal,
filterBySignUpRequired: $scope._filterParamObj.filterBySingupRequired,
filterByPaidOrFree: $scope._filterParamObj.filterByPaid,
filterByEventStatus: $scope._filterParamObj.eventStatusId,
filterByEventType: $scope._filterParamObj.eventTypeId,
selectedTeam: $scope._filterParamObj.seasonTeamId,
filterByStartDate: scheduler.view().startDate(),
filterByEndDate: scheduler.view().endDate(),
OrgId: _orgId,
UserTimezone: global.userTimezoneOffset
}
}
}
},
I am so tired.This code is not change in view date.Please help me
Several issues here - the day view shows just one day; you can't set startDate and endDate - just date.
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
//scheduler.view().startDate(item.StartDate);
//scheduler.view().endDate(item.EndDate);
scheduler.view("day");
// item.StartDate should be Date object - like scheduler.date(new Date("2013/6/6"));
scheduler.date(item.StartDate);
$scope.scheduler.dataSource.read();
};
If you need to set some explicit date range to filter - you can do it, but still you can't show more than just one day in day view.
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler._myFilterStartDate = item.StartDate;
scheduler._myFilterEndDate = item.EndDate;
scheduler.view("day");
scheduler.date(item.StartDate);
$scope.scheduler.dataSource.read();
};
And in parameter map:
...
return {
filterByStartDate: scheduler.view().startDate(),
filterByEndDate: scheduler.view().endDate(),
myFilterStartDate: scheduler._myFilterStartDate,
myFilterEndDate: scheduler._myFilterEndDate,
OrgId: _orgId,
UserTimezone: global.userTimezoneOffset
};
...
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;
When I enter "31/12/2012" in my field (date format is MM/DD/YYYY), it changes the date to "7/12/2014" in the field. I would rather it error with a "not valid" error message.
I have inherited this code from a previous developer:
function dateRangeCheck(val, field) {
field.vtypeText = '';
var date = field.parseDate(val);
if (!date) {
field.vtypeText = val + ' is not a valid date - it must be in the format (MM/DD/YYYY).';
return false;
}
var retVal = true;
if (field.fromField) {
var fromField = Ext.getCmp(field.fromField);
var fromDate = fromField.parseDate(fromField.getValue());
// If we don't have a fromDate to validate with then return true
if (!fromDate)
return true;
retVal = (date >= fromDate);
if (retVal)
fromField.clearInvalid();
}
else if (field.toField) {
var toField = Ext.getCmp(field.toField);
var toDate = toField.parseDate(toField.getValue());
// If we don't have a toDate to validate with then return true
if (!toDate)
return true;
retVal = (date <= toDate);
if (retVal)
toField.clearInvalid();
}
if (!retVal) {
field.vtypeText = 'From Date must be less than or equal to To Date.';
}
return retVal;
}
When I try to use the default 'daterange' vtype, as soon as I type a "3" in the field, it throws a JS runtime exception 'object doesn't support this property or method'.
Note that you can set Date.useStrict = true globally and the DateField will use that by default.
For Ext 4+ it would be Ext.Date.useStrict = true instead.
It looks like your call to parseDate just needs to have the strict switch set.
strict (optional) True to validate date strings while parsing (i.e.
prevents javascript Date "rollover")(defaults to false). Invalid date
strings will return null when parsed.
> Date.parseDate('31/12/2012','m/d/Y')
Sat Jul 12 2014 00:00:00 GMT-0500 (Central Daylight Time)
> Date.parseDate('31/12/2012','m/d/Y', true)
null
The parseDate method in DateField is private and undocumented, and the discussion to allow strict date parsing in ExtJS 3.x never bore any fruit. I think your best bet is to use an override to allow strict date parsing.
// before you use your DateFields
Ext.override(Ext.form.DateField, {
safeParse : function(value, format) {
if (Date.formatContainsHourInfo(format)) {
// if parse format contains hour information, no DST adjustment is necessary
return Date.parseDate(value, format, this.strict);
} else {
// set time to 12 noon, then clear the time
var parsedDate = Date.parseDate(value + ' ' + this.initTime, format + ' ' + this.initTimeFormat, this.strict);
if (parsedDate) {
return parsedDate.clearTime();
}
}
}
});
//... and in your DateField config:
strict: true,