Subtract one day from date and find values -Js - javascript

i working on small billing application using electronjs and pouchdb
i want to find the opening balance for every day based on date selection on input
if there is no data in particular date i want to find the data by the previous dates
i tried in recursive way but it did not work
// getting date value on change
var TodayDate = document.getElementById('daybook-firstdate').value;
// onchange function
function getday(TodayDate){
daybook.find({
selector: {
Date:TodayDate ,
}
}).then(function(result) {
var opening_balance = 0
//chenking the data is present in the selected date
if(result.docs.length>0){
result.docs.forEach((element, ) => {
saletotal = (isNaN(element.TotalAmount) ? 0: parseInt(element.TotalAmount));
Totalinvest = (isNaN(element.TotalInvestment) ? 0: parseInt(element.TotalInvestment));
Totalexp = (isNaN(element.TotalExpenses) ? 0: parseInt(element.TotalExpenses));
opening_balance+=saletotal+Totalinvest-Totalexp
console.log(opening_balance)
});
}
// if there is no data on particular date subtracting one day from date from date and calling the
//get day function with yesterday value as parameter to check if the data is present in previos date
else{
let d = new Date(TodayDate);
d.setDate(d.getDate() - 1);
var yesterdaydate = d.toISOString().split('T')[0];
getday(yesterdaydate)
}
});
}
//selecting the date
<input type="date" name="daybook" id="daybook-firstdate" onchange="getday()" >
i want to execute the find until there is data in previous date from selected date
any one help me with code
day book object: //find is based on Date object

Related

How can I get value entered in to kendo grid date filter input field?

In my grid I have a FromDate field formatted as MM/yyyy, and in the grid of the data source, the FromDate value is in MM/dd/yyyy format. The date is always the first day of the month, so I used jQuery code to set the date value to the first day of the month if the user selects any date using a grid filter calendar or a date picker.
For example, if the user selects or manually enters 11/25/2020 using either the date picker or the keyboard, the jQuery code below sets the date to the first day as 11/1/2020, which works fine. But the problem is if the user enters or types in the date manually in MM/yyyy format or, let's say, enters 11/2020 then nothing happens.
how can I get value entered in to kendo grid date filter input field to apply the same logic below?
if (e.filter.filters[0].field === "FromDate" ) {
var fromDate = e.filter.filters[0].value
var month = fromDate.getMonth();
var year = fromDate.getFullYear();
var firstDateOfTheMonth = new Date(year, month + 1);
var lastDay = firstDateOfTheMonth.getDate();
fromDate.setDate(lastDay);
console.log(e.filter.filters[0]);
var formattedFromDate = moment(fromDate).format('MM/DD/YYYY');
var productsGrid= $("#ProductsGrid").data("kendoGrid");
productsGrid.dataSource.filter({
field: e.filter.filters[0].field,
operator: e.filter.filters[0].operator,
value: formattedFromDate
});
}
Use datepicker change event to trigger your function
$("#datepicker").kendoDatePicker({
change: function() {
var value = this.value();
// logic here
}
});
i fixed smilar problem by this in the grid
->parameterMap('function(options, operation) {
if (options.hasOwnProperty("filter")){
//console.log(options.filter.filters);
var filtre=options.filter.filters;
for(i=0;i<filtre.length;i++){
//console.log(filtre[i].field);
if(filtre[i].field=="date"){
filtre[i].value=kendo.toString(filtre[i].value,"yyyy-MM-dd");
// console.log(kendo.toString(filtre[i].value,"yyyy-MM-dd"));
}
}
}
return kendo.stringify(options);
}'
);

How can I calculate if a Date Object is closer to one or another Date

I am building a calendar where people can select a range of days from a visual calendar.
Clicking on a date will select it as a "from" or "to" date. For example, if I click on 1januari and 5 January. 1 January will be the "from" date while 5 January will be the "to" date. Easy right?
Now the thing is if a user clicks on a new date, I will need to update the current "from" and "to" dates. Using
stringToDate(date.dateTime) > stringToDate(this.state.fromDate)
lets me know if the incoming date is later then the current "from date" with I can use to change the current "to" date to the incoming Date because 7 January comes after 5 January with "must" mean the user wanted to update their "to" date.
A similar function does the same thing for the "from" date. This works great and all but this means that users can't select a "from" date that comes later than their original "from" date.
What I want to achieve is the following: Calculate if the incoming date is closer to the "from" date or the "to" date. So if a user starts with 1 and 5 January and clicks on 2 January I can assume that he wants to update his "from" date.
My current function looks like this:
handleFromDateSelected(date) {
let updatedFromDate = '';
let updatedToDate = '';
if (this.state.fromDate) {
if (stringToDate(date.dateTime) > stringToDate(this.state.fromDate)) {
updatedFromDate = this.state.fromDate;
updatedToDate = date.dateTime;
} else {
updatedFromDate = date.dateTime;
updatedToDate = this.state.fromDate;
}
} else {
updatedFromDate = date.dateTime;
}
this.setState({
fromDate: updatedFromDate,
toDate: updatedToDate,
});
}
If you really want to check from which date the new one is closed, which is, in my opinion not a good choice, you can convert all 3 dates (from, to and new) to timestamp and compare the absolute difference. The lowest one means this is closer to the new one.
in example, let's assume dateFrom, dateTo and newDate are date objects :
//Returns true if newDate is closer to dateFrom
function isFromDateCloser(dateFrom, dateTo, newDate)
{
timeStampFrom = dateFrom.getTime();
timeStampTo = dateTo.getTime();
timeStampNew = newDate.getTime();
return (Math.abs(timeStampFrom - timeStampNew) < Math.abs(timeStampTo - timeStampNew));
}
if (isFromDateCloser(dateFrom, dateTo, newDate))
dateFrom = newDate;
else
dateTo = newDate;
In that example, I've arbitrary choosen that if new date is strictly between both dates, the new date will be dateTo. If you prefer the that the from become the new date, replace in the return < by <=
In your case
var firstDate = new Date(date.dateTime);
var secondDate = new Date(this.state.fromDate)
if (firstDate.getTime() > secondDate .getTime()){
// do something here
}

How to query a timestamp field by year in Feathersjs?

Currently I have a timestamp field with value format like 1479664146607.
What I wanted to do is to get all data with timestamp that has a year of let's say 2017.
My current code is non-performant. It gets all the data, and then uses a filter method.
Let's say I got 2000+ records.
const records = []; // all records
const data = records.filter(r => new Date(r).getYear == '2017');
While this code works, it kills the server.
My database is nedb and using feathersjs, I can actually get equality items by
app.service('messages').find({
query: {
timestamp: '2017'
}
});
This code will not work because it will search for the exact year. I am looking for a way to convert the timestamp field to a year before searching it in the database.
Okay, so what I did is to use the $gt and $lt operators.
Let's say we want to get all data in year 2018.
Using momentjs, I did something like this:
const year = '2018';
// Get previous year based on given year
const previousYear = moment(year, 'YYYY').subtract(1, 'year').format('YYYY');
// Get next year based on given year
const nextYear = moment(year, 'YYYY').add(1, 'year').format('YYYY');
// get full ending date of previous year
const endOfPreviousYear = moment(previousYear, 'YYYY').endOf('year').format('x');
// get full starting date of next year
const startOfNextYear = moment(nextYear, 'YYYY').startOf('year').format('x');
// get data where year is greater than `endOfPreviousYear` and less than `startOfNextYear`
const yearQuery = {
$gt: +endOfPreviousYear,
$lt: +startOfNextYear
}
app.service('messages').find({
query: {
timestamp: yearQuery
}
});

How to put basic date validations in mirth javascript

We currently accept HL7 data through mirth and one of the field we process is date of birth, which we receive in PID.7.1 segment of HL7. Currently we just capture it like -
var vDOB = formatDate(msg['PID.7.1'].toString(),"yyyyMMdd");
How can I validate day , month and year component in the date. And also like it should be greater than today's date.
Thanks
You can include a function like this:
var dateChecker = function(dateStr){
if(date.length !=8 && !date.match('[0-9]{8}')) return false;//should be number and length 8
var year = date.substr(0,4);
var month = date.substr(4,2);
var day = date.substr(6,2);
var dateObj = new Date(year,month,day);
if (dateObj == 'Invalid Date') return false;
if(dateObj.getTime() - Date.now() > 0) return false;//compare epoch to check if date is less than current date/time
return true;
}
and then dateChecker(vDOB) should return true/false depending on whether the date is valid or invalid.

react AG-grid: date filter in range - doesn't work if you reverse the dates

I'm trying to set up a date filter on ag-grid as per this link.
The main difference is that ag-grid prefers date format dd/mm/yyyy whereas my dates are in yyyy-mm-dd.
comparator:function (filterLocalDateAtMidnight, cellValue){
let dateParts = cellValue.split("-");
let cellDate = new Date(Number(dateParts[0]), Number(dateParts[1]) - 1, Number(dateParts[2]));
if (cellDate < filterLocalDateAtMidnight) {
return -1;
} else if (cellDate > filterLocalDateAtMidnight) {
return 1;
} else {
return 0;
}
The above code works conventionally, although I noticed a special case.
when selecting the date filter condition "inRange", and setting the dates e.g:
dateFrom = 2017-07-13
dateTo = 2017-08-20
it works fine and i see records between those two dates, but if you reverse the dates, i.e.:
dateFrom = 2017-08-20
dateTo = 2017-07-13
No records show. How can I overcome this glitch? Conventionally, the user would put the earliest date first, but that doesn't mean the above scenario isn't possible

Categories