How to calculate age of users when they are entered their date of birth in react-native? - react-native

How to calculate age of users when they are entered their date of birth in react-native?
I want to check user is more then 18 year or not.When they are entered date of birth .
I am using react-native-datepicker for take user's date of birth.
I am trying to calculate age of user using below code but it not work properly .So please help me .How i can achieve this functionality.
calculate_age = (date) => {
var today = new Date();
var birthDate = new Date(date);
console.log("get bod-->",birthDate) // create a date object directly from `dob1` argument
var age_now = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age_now--;
}
console.log('my age', age_now);
return age_now;
}
onDateChange = (date) => {
this.setState({ date: date }, () => {
console.log(date)
if (this.calculate_age(date) < 18) {
alert("You Are Not Eligable")
} else {
}
})
}

Using 'npm i moment' package.I solved this problem.
onDateChange = (date) => {
this.setState({ date: date }, () => {
if (this.calculate_age(Moment(date,"DD-MM-YYYY").format("YYYY-MM-DD")) <= 17 ) {
this.setState({errmsg:"You must be atleast 18 years of old to join."})
}else{
this.setState({errmsg:" "})
}
})
}

You can make a custom function like this:
const getAge = (dateString)=>{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
console.log('age: ' + getAge("1980/08/10"));

Related

Variable is not modified in this loop - no-unmodified-loop-condition from ESLint

I have a project where ESLint throws this error from while loop. It does not make sence to me. Error says:
497:14 error 'from' is not modified in this loop no-unmodified-loop-condition
497:22 error 'to' is not modified in this loop no-unmodified-loop-condition
This is the code (look at while cycle):
mediaSettings: (state) => {
const timestamps = [];
const events = [];
state.media.forEach( medium => {
if( !medium.settings.dates ) return;
medium.settings.dates.forEach( dateRange => {
if( !dateRange.date_from || !dateRange.date_to ) return;
const from = new Date( dateRange.date_from );
const to = new Date( dateRange.date_to );
while ( from <= to ) {
if( timestamps.includes(from.getTime()) ) {
from.setDate( from.getDate() + 1 );
continue;
}
events.push({
date: new Date( from.getTime() ), // Need Date clone via new Date().
mediumId: medium.id,
});
from.setDate( from.getDate() + 1 );
};
});
});
return events;
}
What is that? Can somebody tell me plase how to fix it? It does not make sence. This is not an error.
I found clever solution on this page which disables ESLint for some block of code and also a specific ESLint rules. It looks like:
mediaSettings: (state) => {
const timestamps = [];
const events = [];
state.media.forEach( medium => {
if( !medium.settings.dates ) return;
medium.settings.dates.forEach( dateRange => {
if( !dateRange.date_from || !dateRange.date_to ) return;
const from = new Date( dateRange.date_from );
const to = new Date( dateRange.date_to );
/* eslint-disable no-unmodified-loop-condition */
while ( from <= to ) {
if( timestamps.includes(from.getTime()) ) {
from.setDate( from.getDate() + 1 );
continue;
}
events.push({
date: new Date( from.getTime() ), // Need Date clone via new Date().
mediumId: medium.id,
});
from.setDate( from.getDate() + 1 );
};
/* eslint-enable no-unmodified-loop-condition */
});
});
return events;
}
You wouldn't get this error if you are using reassignable variables like this:
...
let from = new Date(dateRange.date_from)
let to = new Date(dateRange.date_to)
while (from <= to) {
if (timestamps.includes(from.getTime())) {
from = from.setDate(from.getDate() + 1)
continue
}
events.push({
date: new Date(from.getTime()), // Need Date clone via new Date().
mediumId: medium.id,
})
from = from.setDate(from.getDate() + 1)
}
...

Highcharts with decrease order in each interval

Is it possible to create a graph sorted in each time interval using Highcharts?
For expample, in this picture for January data will be in order: New York, Tokyo, London, Berlin. The same for each months - data should be shown decrease order
Highcharts doesn't have a built-in function to do that, but for example you can use the render event and organize columns, by changing their positions in the way you need.
events: {
render: function() {
var series = this.series,
longestSeries = series[0],
sortedPoints = [],
selectedPoints = [];
// find a series with the highest amount of points
series.forEach(function(s) {
if (s.points.length > longestSeries.points.length) {
longestSeries = s;
}
});
longestSeries.points.forEach(function(point) {
series.forEach(function(s) {
selectedPoints.push(s.points[point.index]);
});
sortedPoints = selectedPoints.slice().sort(function(a, b) {
return b.y - a.y;
});
selectedPoints.forEach(function(selectedPoint) {
if (
selectedPoints.indexOf(selectedPoint) !==
sortedPoints.indexOf(selectedPoint) &&
selectedPoint.graphic
) {
// change column position
selectedPoint.graphic.attr({
x: sortedPoints[selectedPoints.indexOf(selectedPoint)].shapeArgs.x
});
}
});
sortedPoints.length = 0;
selectedPoints.length = 0;
});
}
}
Live demo: https://jsfiddle.net/BlackLabel/tnrch8v1/
API Reference:
https://api.highcharts.com/highcharts/chart.events.render
https://api.highcharts.com/class-reference/Highcharts.SVGElement#attr
#ppotaczek Thank You for help a lot! I solve my issue, but i had to make some changes to your code:
events: {
render: function() {
if (this.series.length === 0) return
var series = this.series,
longestSeries = series[0],
sortedPoints = [],
selectedPoints = [];
// find a series with the highest amount of points
series.forEach(function(s) {
if (s.points.length > longestSeries.points.length) {
longestSeries = s;
}
});
longestSeries.points.forEach(function(point) {
series.forEach(function(s) {
selectedPoints.push(s.points[point.index]);
});
sortedPoints = selectedPoints.slice().sort(function(a, b) {
return b.y - a.y;
});
selectedPoints.forEach(function(selectedPoint) {
if (
selectedPoints.indexOf(selectedPoint) !==
sortedPoints.indexOf(selectedPoint) &&
selectedPoint.graphic
) {
// change column position
selectedPoint.graphic.attr({
x: selectedPoints[sortedPoints.indexOf(selectedPoint)].shapeArgs.x
});
}
});
sortedPoints.length = 0;
selectedPoints.length = 0;
});
}
},
}
So i changed:
// change column position
selectedPoint.graphic.attr({
x: sortedPoints[selectedPoints.indexOf(selectedPoint)].shapeArgs.x
});
to:
// change column position
selectedPoint.graphic.attr({
x: selectedPoints[sortedPoints.indexOf(selectedPoint)].shapeArgs.x
});

Use filter in Vue3 but can't read globalProperties

Just a quick question,
I know that Vue3 doesn't use filters anymore and notes says use computed or methd instead. but also there is a globalProperties we can use,
I used this globalProperties but keep getting this error
Uncaught TypeError: Cannot read property 'globalProperties' of undefined
Does anyone know where is the bug in my code?
const app = {
data() {
return {
message: ""
}
}
}
app.config.globalProperties.$filters = {
formatDate(value) {
if (value == "0001-01-01T00:00:00")
return "";
var today = new Date(value);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
return today;
}
}
Vue.createApp(app).mount('#app');
And I am using the filter in my table like this
<td>
{{ $filters.formatDate(incident.incidentData) }}
</td>
The config field belongs to the root instance not to the root component so you should do:
const app = {
data() {
return {
message: ""
}
}
}
const myApp=Vue.createApp(app)
myApp.config.globalProperties.$filters = {
formatDate(value) {
if (value == "0001-01-01T00:00:00")
return "";
var today = new Date(value);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
return today;
}
}
myApp.mount('#app');
Vue.createApp(app) return the root instance
myApp.mount('#app'); after mounting root app to an element it returns the root component

Subtract 2 times in react-native

I want to subtract two times and check if check_in time > 12Hr then navigate to checkin screen. This is my code snippet
class SplashView extends Component {
componentDidMount() {
const curr_time = moment().format('hh:mm:ss');
const checkin_time = moment(this.props.datetime).format('hh:mm:ss');
// const diff = moment.duration(checkin_time.diff(curr_time));
console.log("TIME&&&&&&&&", curr_time, checkin_time);
setTimeout(() => {
if (this.props.employee_id === null) {
this.props.navigation.navigate('Login');
} else {
this.props.navigation.navigate('Checkin');
}
}, 1000)
}
render() {
return ();
}
}
I'm using moment.js and the value of this.props.datetime is '2019-02-04 14:52:01'. This is my checkin time.
You can get the difference in hours like this:
const diff = moment.duration(checkin_time.diff(curr_time)).as('hours');
Or you can just use moment's diff function
const diff = checkin_time.diff(curr_time, 'hours')
and then compare if (diff > 12) { ... }

Dojo dgrid: Filter data from store with diffrent fields when I click on filter button

I am using 'dgrid/Grid' and dstore/RequestMemory for creating grid and storing data. Now I want to filter data according to values in the fields(see img). I am not sure how to filter data when using simple Dgrid and dstore.
var structure = [{
label : "Value Date",
field : "valueDate"
}, {
id: "currencyCol",
label : "Currency",
field : "currency"
}, {
label : "Nostro",
field : "nostroAgent"
}];
var store= new RequestMemory({
target: 'getReportData',
idProperty: "cashflowId",
headers: structure
});
// Create an instance of OnDemandGrid referencing the store
var grid = new(declare([Grid, Pagination, Selection]))({
collection: store,
columns: structure,
loadingMessage: 'Loading data...',
noDataMessage: 'No results found.',
minRowsPerPage: 50,
}, 'grid');
grid.startup();
on(document.getElementById("filter"), "click", function(event) {
event.preventDefault();
grid.set('collection', store.filter({
**currencyCol: "AED"**
.
.
.
}));
Any help would be appreciated or suggest if I use some diffrent store or grid.
I got the solution for my question. On filter button click I have written all my filtering logic and the final store will set to dgrid:
on(document.getElementById("filter"), "click", function(event) {
var store= new RequestMemory({
target: 'getReportData',
idProperty: "cashflowId",
headers: structure
});
var from=dijit.byId('from').value;
var to=dijit.byId('to').value;
var curr=dijit.byId('currency').value;
var nos=dijit.byId('nostro').value;
var authStatus=dijit.byId('authStatus').value;
var filterStore;
var finalStore=store;
var filter= new store.Filter();
var dateToFindFrom;
var dateToFindTo;
if (from != "" && from !== null) {
var yyyy = from.getFullYear().toString();
var mm = ((from.getMonth()) + 1).toString(); // getMonth() is zero-based
var dd = from.getDate().toString();
if(mm <= 9){
mm= "0" + mm;
}
if(dd <= 9){
dd= "0" + dd;
}
dateToFindFrom =yyyy + mm + dd;
filterStore= filter.gte('valueDate', dateToFindFrom);
finalStore=finalStore.filter(filterStore);
}
if (to != "" && to !== null) {
var yyyy = to.getFullYear().toString();
var mm = ((to.getMonth()) + 1).toString(); // getMonth() is zero-based
var dd = to.getDate().toString();
if(mm <= 9){
mm= "0" + mm;
}
if(dd <= 9){
dd= "0" + dd;
}
dateToFindTo =yyyy + mm + dd;
filterStore= filter.lte('valueDate', dateToFindTo); //.lte('valueDate', dateToFindTo);
finalStore=finalStore.filter(filterStore);
}
if(curr != "" && curr !== null) {
filterStore= filter.eq('currency', curr);
finalStore=finalStore.filter(filterStore);
}
if(nos != "" && nos !== null) {
filterStore= filter.eq('nostroAgent',nos);
finalStore=finalStore.filter(filterStore);
}
if(authStatus != "" && authStatus !== null) {
if (authStatus=='ALL') {
var both= [true, false];
filterStore= filter.in('approved', both);
finalStore=finalStore.filter(filterStore);
} else if (authStatus=='Authorised Only') {
filterStore= filter.eq('approved', true);
finalStore=finalStore.filter(filterStore);
} else if (authStatus=='Unauthorised Only') {
filterStore= filter.eq('approved', false);
finalStore=finalStore.filter(filterStore);
};
};
grid.set('collection', finalStore);
});