How can i get all the previous months since today? - react-native

How can i do this same function of this with moment js or other library like luxon, i want to get all the previos 'n' months since the current day
for example currently is agost, i need Feb, Mar, Apr, May, Jun, Jul, the names should be in short
console.log(getPreviousNMonths(6))
function uInt(n, ceil) {
while (n < 0) {
n += ceil
}
return n % ceil
}
function getPreviousNMonths(n) {
const date = new Date()
const d = new Date(date.getTime())
const formatter = new Intl.DateTimeFormat([], { month: 'short' })
const names = []
for (let i = 0; i < n; i += 1) {
d.setMonth(uInt(d.getMonth() - 1, 12))
names.push(formatter.format(d))
}
return names.reverse()
}

Using moment.js
const names = []
for (let i = 1; i <= n; i += 1) {
let monthName = moment('2021-08-10').subtract(i, "month").startOf("month").format('MM');
names.push(monthName)
}
Or using luxon
const names = []
for (let i = 1; i <= n; i += 1) {
let monthName = DateTime.local().minus({ months: i }).toFormat("MM")
names.push(monthName)
}

Related

In JavaScript, retrieve the value and performed the addition after that want to return the value after the for loop in cypress automation?

verifyActiveInterfacesViaConnectionStatus() {
var sum = 0
var i;
for (i = 1; i <= 5; i++) {
cy.xpath(`(//*[name()='g' and #class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[#class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {
var textValue1 = $text1 + "\n"
cy.log(textValue1)
var total = parseInt(textValue1)
sum += total
})
}
cy.log("Total of all connected OS= " + sum)
}
In the cypress automation, when I'm running this block of code it is returning the sum=0 but I don't know why it is displaying 0. Please help me out.
Cypress commands are asynchronous.
cy.log captures the sum value before the first xpath command gets really executed.
To synchronize access to the sum you can use a then callback:
verifyActiveInterfacesViaConnectionStatus() {
var sum = 0
var i;
for (i = 1; i <= 5; i++) {
cy.xpath(`(//*[name()='g' and #class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[#class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {
var textValue1 = $text1 + "\n"
cy.log(textValue1)
var total = parseInt(textValue1)
sum += total
})
}
cy.then(() => {
cy.log("Total of all connected OS= " + sum)
})
}
Look at this article for details on how to handle variables at Cypress.

Expand Text of Compact Data

I am stuck with some data manipulation.
This is a small portion of the input data (df):
site=c("C000-C002","C420-C421,C424")
histology=c("9835-9836","9811-9812,9837")
category=c("Leukemia","Leukemia")
df=data.frame(site,histology,category)
And this is what I want the processed data to look like:
You may assume Site and Histology are both 4-digit after text splitting.
In case anyone is interested, the full data table is here
Please help with the text processing, or if anyone knows an existing processed package or database in a similar format as the image, that would be great too.
Thank you very much.
I don't know R language. So I tried with Javascript as following.
function mapStartEnd(start, end) {
let list = [];
let info = {};
const siteStart = start.match(/([A-Z])(\d{3})/);
if (siteStart) {
const siteEnd = end.match(/([A-Z])(\d{3})/);
info = {
type: "site",
prefix: siteStart[1],
numLength: 3,
from: parseInt(siteStart[2], 10),
to: parseInt(siteEnd[2], 10),
};
}
const histologyStart = start.match(/\d{4}/);
if (histologyStart) {
const histologyEnd = end.match(/\d{4}/);
info = {
type: "histology",
prefix: "",
numLength: 4,
from: parseInt(histologyStart[0], 10),
to: parseInt(histologyEnd[0], 10),
};
}
const categoryStart = start.match(/[A-Z][a-z]+/);
if (categoryStart) {
const categoryEnd = end.match(/[A-Z][a-z]+/);
info = {
type: "category",
prefix: "",
numLength: 0,
from: categoryStart[0],
to: categoryEnd[0],
};
}
if (!info.numLength) {
list = [info.from, info.to];
} else {
for (let i = info.from; i <= info.to; i++) {
list.push(info.prefix + i.toString().padStart(info.numLength, "0"));
}
}
return list;
}
function c(list) {
return list.map((list2) => {
return list2.split(",").reduce((prev, cur) => {
const [start, end] = cur.split("-");
if (!end) prev.push(start);
else prev = [...prev, ...mapStartEnd(start, end)];
return prev;
}, []);
});
}
function map3(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
for (let j = 0; j < histologys.length; j++) {
const histology = histologys[j];
for (let k = 0; k < categorys.length; k++) {
const category = categorys[k];
// JSON format
// list.push({ site, histology, category });
// CSV format
list.push(`${site},${histology},${category}`);
}
}
}
return list;
}
function frame(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
const histology = histologys[i];
const category = categorys[i];
list = [...list, ...map3(site, histology, category)];
}
return list;
}
const site = c(["C000-C002", "C420-C421,C424"]);
const histology = c(["9835-9836", "9811-9812,9837"]);
const category = c(["Leukemia", "Leukemia"]);
const df = frame(site, histology, category);
console.log(df);
Result:
[
"C000,9835,Leukemia",
"C000,9836,Leukemia",
"C001,9835,Leukemia",
"C001,9836,Leukemia",
"C002,9835,Leukemia",
"C002,9836,Leukemia",
"C420,9811,Leukemia",
"C420,9812,Leukemia",
"C420,9837,Leukemia",
"C421,9811,Leukemia",
"C421,9812,Leukemia",
"C421,9837,Leukemia",
"C424,9811,Leukemia",
"C424,9812,Leukemia",
"C424,9837,Leukemia"
]
https://jsfiddle.net/dnu2g0vr/

How to calculate age of users when they are entered their date of birth in 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"));

DataTables - filtering based on time span

I have a column with data, within the datatables, similar to the below:
0500-1300
0500-1430
0600-0915
0600-1000
0600-1100
0600-1115
0600-1130
0600-1200
0600-1215
0600-1300
0600-1315
I would like a filter not too dissimilar from http://yadcf-showcase.appspot.com/dom_bootstrap_time.html where someone can pick a FROM time and a TO time, which would then filter the data.
Let's say say someone chooses:
FROM: 0600
TO: 1100
Then only 3 would show. However if I chose:
FROM: 0500
TO: 1400
All would show. Is such a thing possible? Would the plugin from the site above be what I am after?
Try this:
const timeStringToInt = (time) => {
const hoursMinutes = time.split(/[.:]/);
const hours = parseInt(hoursMinutes[0], 10) * 60;
var minutes = parseInt(hoursMinutes[1], 10);
return hours + minutes;
}
$.fn.dataTable.ext.search.push(
(settings, data, dataIndex) => {
const min = timeStringToInt($('#timeFrom').val());
const max = timeStringToInt($('#timeTo').val());
const start = timeStringToInt(data[0]);
const end = timeStringToInt(data[1]);
return start >= min && end <= max;
}
);
You might need to alter your function depending upon the position of the hours columns. Working JSFiddle here.
EDIT
After looking at your data a little more I made a mistake in my initial answer, this should do it:
const timeStringToInt = (time) => {
const hoursMinutes = time.split(":");
const hours = parseInt(hoursMinutes[0], 10) * 60;
var minutes = parseInt(hoursMinutes[1], 10);
return hours + minutes;
}
const stringToInt = (time) => {
var minutes = parseInt(time.slice(-2), 10);
const hours = parseInt(time.slice(0, -2), 10) * 60;
return hours + minutes;
}
$.fn.dataTable.ext.search.push(
(settings, data, dataIndex) => {
const min = timeStringToInt($('#timeFrom').val());
const max = timeStringToInt($('#timeTo').val());
const timeParts = data[0].split("-");
const start = stringToInt(timeParts[0]);
const end = stringToInt(timeParts[1]);
return start >= min && end <= max;
}
);
Updated JSFiddle here.
Hope that helps :-)

Create a running sum graph in dc.js

I am trying to create a running sum in crossfilter to use with dc.js.
I have a set of records like the following :
records = [{"date":"2014-01-01","field1":"value1","field2":"value11","value_field":-20},
{"date":"2014-01-02","field1":"value2","field2":"value12","value_field":100},
{"date":"2014-01-03","field1":"value1","field2":"value11","value_field":-10},
{"date":"2014-01-04","field1":"value2","field2":"value12","value_field":150},
]
So far I have created a barGraph which plays nicely with the other dimensions but I would like to be able to show an line graph of the theoretical field runnning_total (along the dimension date).
To have it done in crossfilter would allow me to then group using the fieldx fields and easily get the same running total graph but restricted to a subgroup of values using dc.js.
Any help is welcome.
Since you are grouping across date (as per your date dimension), the reduce() function would be used to perform aggregations grouped by date, as per the highlighted cells in my Mickey Mouse example below:
With a running total you'd need to perform an entirely different operation, looping down the rows:
You can aggregate the data and then append the running total field as follows. I've also included an example of how to calculate an average value, using the reduce function:
records = [{ "date": "2014-01-01", "field1": "value1", "field2": "value11", "value_field": -20 },
{ "date": "2014-01-02", "field1": "value2", "field2": "value12", "value_field": 100 },
{ "date": "2014-01-03", "field1": "value1", "field2": "value11", "value_field": -10 },
{ "date": "2014-01-04", "field1": "value2", "field2": "value12", "value_field": 150 }
];
var cf = crossfilter(records);
var dimensionDate = cf.dimension(function (d) {
return d.date;
});
function reduceAdd(p, v) {
p.total += v.value_field;
p.count++;
p.average = p.total / p.count;
return p;
}
function reduceRemove(p, v) {
p.total -= v.value_field;
p.count--;
p.average = p.count ? p.total / p.count : 0;
return p;
}
function reduceInitial() {
return {
total: 0,
count: 0,
average: 0,
};
}
var average = dimensionDate.group().reduce(reduceAdd, reduceRemove, reduceInitial).all();
var averageWithRunningTotal = appendRuningTotal(average);
function appendRuningTotal(average) {
var len = average.length,
runningTotal = 0;
for (var i = 0; i < len; i++) {
runningTotal += average[i].value.total;
average[i].RunningTotal = runningTotal;
}
return average;
}
And this returns the following:
{"key":"2014-01-01","value":{"total":-20,"count":1,"average":-20},"RunningTotal":-20}
{"key":"2014-01-02","value":{"total":100,"count":1,"average":100},"RunningTotal":80}
{"key":"2014-01-03","value":{"total":-10,"count":1,"average":-10},"RunningTotal":70}
{"key":"2014-01-04","value":{"total":150,"count":1,"average":150},"RunningTotal":220}
Well I know the op already built a solution but after struggling with for a while I was able to crack it, so posting it here if someone else searches for it.
using the cumulative for the following: https://groups.google.com/forum/#!topic/dc-js-user-group/W9AvkP_dZ0U
Running Sum:
var _group = dim.group().reduceSum(function(d) {return 1;});
var group = {
all:function () {
var cumulate = 0;
var g = [];
_group.all().forEach(function(d,i) {
cumulate += d.value;
g.push({key:d.key,value:cumulate})
});
return g;
}
};
for Trailing Twelve Month calculation:
var _group = dateDim.group().reduceSum(function(d) {return d.revenue;});
var group = {
all:function () {
var g = [];
_group.all().forEach(function(d,i) {
var cumulate = 0;
var monthcount =0;
var dt =new Date( d.key);
var ct = new Date(d.key);
ct.setFullYear(ct.getUTCFullYear() -1);
_group.all().forEach(function(d2,i) {
var dt2 = new Date(d2.key);
if(dt2 <= dt && dt2 > ct){
cumulate += d2.value;
monthcount++;
}
})
if(monthcount>=11){
console.log( ' Dt ' + dt + ' ' + cumulate + ' months ' + monthcount);
g.push({key:d.key,value:cumulate})
}
});
return g;
}
};