I want to get date of birth of a user, with predefined min and max date which is working fine.
And the date format i want is DD-MM-YYYY, for this i have defined following in config;
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
and the controller has
$scope.user = {};
$scope.user.dob = new Date();
$scope.maxDate = new Date(
$scope.user.dob.getFullYear() - 10,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
$scope.minDate = new Date(
$scope.user.dob.getFullYear() - 120,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
and the HTML is;
<md-datepicker
ng-model="user.dob"
md-placeholder="Enter date of birth"
md-min-date="minDate"
md-max-date="maxDate">
</md-datepicker>
with this code the field shows current date by default, which i don't want,
i want the date field to be empty by default.
Also i want to get values in both ways as follows
1) date-month-year
And
2) date-month-year hour-minutes-seconds
When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"
i want either "09-11-2016" or "09-11-2016 18:30:00"
Your mdDateLocaleProvider doesnt check for null values.
Your Problem is:
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
it needs to be something like:
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid()? m.format('DD-MM-YYYY') : '';
};
Then you can set
$scope.user.dob=null;
And get an empty Datepicker.
The problem is your ng-model. You're initializing it with the current date:
$scope.user.dob = new Date();
Simply empty this variable and you'll be good ;)
Related
I want to initially display the last month's last date, for example, this is November, I want to display 31/10/2019. How is it possible?
var date = new Date();
date.setMonth(date.getMonth())
const firstDayOfCurrent = new Date(date.getFullYear(), date.getMonth(), 0);
const firstDayOfCurrentMonth = moment(firstDayOfCurrent).format('MM/DD/YYYY')
console.log(firstDayOfCurrentMonth);
<td><input type="date" value={firstDayOfCurrentMonth} onChange={(e) => { this.state.invoice.InvoiceDateString = e.target.value; this.setState({ isset: true }); }} required /></td>
This code snippet will give you last date of last month
var date = new Date();
date.setMonth(date.getMonth())
var lastDay = new Date(date.getFullYear(), date.getMonth(), 0);
var lastDayOfLastMonth = lastDay.toISOString().substr(0, 10);
and your input tag
<input type="date" defaultValue={lastDayOfLastMonth } required />
You can take month from current date to take first day of current month and then subtract one day:
const today = new Date();
const firstDayOfCurrentMonth = new Date(today.getFullYear(), today.getMonth(), -1);
``
I would recommend to use date-fns, which has a ton of helper functions you could use for that use-case.
For example lastDayOfMonth, which returns the last day of the month.
It also allows tree-shacking, so that you do not import the whole library, but only the functions you use.
I have a date as "2017-04-03 05:00:07". I need to check for the date is today's date. If it is today's date i need to display as today or time.
If it is yesterday's need to display as yesterday or date as "MMM dd"
If it is last month or with in this year then, "MMM dd".
If it is last year then dd/mm/yyyy
I tried to display like this using a directive but this is not working for me.
Is there anyother way?
app.directive('myDirective', function($filter) {
return {
restrict: "A",
scope: {
myDirective: '='
},
link: function(scope, element, attrs) {
var date1 = new Date(scope.myDirective.updateddate);
var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays == 1) {
scope.myDirective.updateddate = 'yesterday'
} else if (diffDays > 2 && diffDays <= 365) {
scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MMM');
}
else if (diffDays > 365) {
scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MM-YYYY');
} });
Use Moment.js while displaying like
{{moment(date).calendar()}} // Today at 11:17 AM
For reference: https://momentjs.com/
Using a custom filter is the most correct approach to this.
You define a filter much like a directive:
app.filter('myfilternamehere', function() {
return function(input) {
//do some stuff that creates the correct output
return output;
}
});
I have created a JSFiddle that might contain a solution for your problem and at the same time shows you how to create a custom directive in a bit more detail.
I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
i am displaying date like :
{{ friend.birthday }}
How can i display age instead of displaying birthday.
if it is possible to create filters than how to create filter and how to apply it.
You can implement a function:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(friend.birthday) }}
Or a filter:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
HTML
{{ friend.birthday | ageFilter }}
Age algorithm taken from this SO answer.
[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
If you're value is just for example "05/01/2016". This will be a useful code to convert the date to birthday.
AngularJS
app.filter('ageFilter', function(){
return function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
});
HTML
{{ relationTypePreDefined.birthdate | ageFilter }}
By the way I used this solution to convert a date coming from a jquery datepicker input to age.
If you are using momentjs. Then you can create filter simply by using this snippet
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Idk why I can never reply to people, says I need more rep but to rep I need to comment.. whatever.
In response to #Dean Christian Armada's, I kept getting an error regarding the filter. But changing to the following seems to work fine so I do appreciate it!
$scope.getAge = function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
And for the HMTL
{{ getAge(birthdate) }}
I wanted to set different date in Extjs date picker by replacing default date of date picker that comes system date.
for that I override Date field - below is my code -
Ext.override(Ext.form.field.Date, {
expand: function() {
var value = this.getValue();
var customDate = '07/08/2013';
var myDate = new Date(customDate );
this.getPicker().setValue(Ext.isDate(value) ? value : myDate);
}
});
Now I was expecting myDate as default in picker.
But picker is not populating when I click on picker to select date.
Thanks
I fixed the issue myself. Here is the code to do that. Hopefully it will help someone and will save precious time.
Ext.override(Ext.form.field.Date, {
expand: function() {
var myDate = new Date('07/08/2017');
var value = this.getValue();
this.getPicker().setValue(Ext.isDate(value) ? value : myDate);
var me = this, bodyEl, picker, collapseIf;
if (me.rendered && !me.isExpanded && !me.isDestroyed) {
bodyEl = me.bodyEl;
picker = me.getPicker();
collapseIf = me.collapseIf;
me.isExpanded = true;
me.alignPicker();
bodyEl.addCls(me.openCls);
me.mon(Ext.getDoc(), {
mousewheel: collapseIf,
mousedown: collapseIf,
scope: me
}); Ext.EventManager.onWindowResize(me.alignPicker, me);
me.fireEvent('expand', me);
}
}
});
I have an ExtJS Date field. During some operation in the application, min value and max value get assigned to the date field. The min value and max value are 4 years prior to the current dat, but when the date picker opens up, it opens to the disabled current dates. The user has to manually scroll back 4 years to select a date. Anyways I can update the datepicker to open up by showing the date between the min value and max value ?
Adding code:
cmpDt.setMinValue(new Date(2000, 0, 1));
cmpDt.setMaxValue(new Date(2004, 0, 1));
this sets the min and max value. I cant use setValue() because it inialises/changes the textfield. I want the textfield to get value only on selection from the datepicker.
Thanks
You have to set an initial value using the value property of the Ext.form.field.DateView:
{
...,
minValue: new Date(2000, 0, 1),
maxValue: new Date(2004, 11, 31),
value: new Date(2002, 5, 15),
...
}
EDIT after more info from the OP:
You may override the onExpand method that initializes the value on the picker. The original one looks like (given that you use ExtJS 4 - but 3 should not be that much different):
...,
onExpand: function() {
var value = this.getValue();
this.picker.setValue(Ext.isDate(value) ? value : new Date());
},
...
You could override the method to read:
...,
onExpand: function() {
var value = this.getValue(),
myDefaultDate = /* do some processing to determine the default date*/;
this.picker.setValue(Ext.isDate(value) ? value : myDefaultDate);
},
...
Just add the override to the initial form field configuration.
For anyone interested in an EXTJS 3 solution to this problem, I've made the following code.
This allows you to pass initialDateToShowOnPicker as a config to the Ext.DatePicker when declaring it, if needed.
It also allows you to call setInitialDateToShowOnPicker(initialDateToShowOnPicker) on the datepicker component to set it dynamically.
Both require a Date() type to be used, and there cannot be a value already set on the datepicker.
if (Ext.versionDetail && Ext.versionDetail.major == 3) {
Ext.form.DateField.prototype.setInitialDateToShowOnPicker = function (initialDateToShowOnPicker) {
this.initialDateToShowOnPicker = initialDateToShowOnPicker;
};
Ext.form.DateField.override({
onTriggerClick: function() {
if(this.disabled){
return;
}
if(this.menu == null){
this.menu = new Ext.menu.DateMenu({
hideOnClick: false,
focusOnSelect: false
});
}
this.onFocus();
Ext.apply(this.menu.picker, {
minDate : this.minValue,
maxDate : this.maxValue,
disabledDatesRE : this.disabledDatesRE,
disabledDatesText : this.disabledDatesText,
disabledDays : this.disabledDays,
disabledDaysText : this.disabledDaysText,
format : this.format,
showToday : this.showToday,
startDay: this.startDay,
minText : String.format(this.minText, this.formatDate(this.minValue)),
maxText : String.format(this.maxText, this.formatDate(this.maxValue)),
initialDateToShowOnPicker: this.initialDateToShowOnPicker // Date() type
});
this.menu.picker.setValue(this.getValue() || this.initialDateToShowOnPicker || new Date());
this.menu.show(this.el, "tl-bl?");
this.menuEvents('on');
}
}); }