NetSuite - excluding weekends from date calculation - javascript

My scheduled script sets a field to store an accrued late fee charge for each day an invoice is overdue. I am comparing the current system time against due date to work out the number of days overdue. However, I didn't take into consideration to exclude the weekend. How can I use my existing code to do this?
var current_date = nlapiStringToDate(nlapiDateToString(new Date()));
var dd = invoice.getFieldValue('duedate');
var due_date = nlapiStringToDate(dd);
if (due_date < current_date) {
//Other Calculations
var days_overdue = DateOverdue(current_date, due_date);
}
function DateOverdue(current_date, due_date) {
var time_difference = Math.abs(due_date.getTime() - current_date.getTime());
var no_days_overdue_by = Math.ceil(time_difference / (1000 * 3600 * 24));
return no_days_overdue_by;
}

The following works. Note the extra dates are to clear issues from comparing time stamps without hours, minutes and seconds. Not strictly needed for the current_date given how you are generating it but it makes a more general function.
NOTE: I don't believe you should be able to compare dates with d1 < d2.
function daysOverdue(currentDate, dueDate){
var days = 0;
var due = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate(), 0, 0, 0);
var fromTS = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0).getTime();
if(due.getTime() >= fromTS) return 0; // not overdue
while(due.getTime() < fromTS){
if(due.getDay() !== 0 && due.getDay() != 6) days++;
due.setDate(due.getDate() + 1);
}
return days;
}

Related

How to display time range on iteration?

I am trying to run a for loop that has to loop 8 times. On each iteration I want the loop to increment the value by +1 hour.
The final output should be in this time format:
opening hours:
08:00, 09:00, 10:00,11:00, 12:00, 13:00, 14:00, 15:00,16:00
In this case timediff mentioned in the for...loop holds the value of 8.
var minutesToAdd = 60;
var currentDate = new Date("2022-04-10 08:00:00");
var futureDate = new Date(currentDate.getTime() + minutesToAdd * 120000).toLocaleTimeString();
for (let i = 0; i < timeDiff; i++) {
console.log(futureDate, 'futureeee date');
}
Your code never updates futureDate in the loop. Also, when you expect to print 08:00 in the example, you should print currentDate when no minutes have been added yet.
I would also suggest you use the native function setMinutes and getMinutes to add a number of minutes to a date object.
You say that timeDiff has a value of 8, but then you say you want 9 outputs (8:00 ... 16:00), so you'll need an additional iteration.
Finally, to get the hh:mm output format, there are several solutions. One is to choose a locale that uses a format that is close to what you need, and express you want the short format (without seconds):
let timeDiff = 9; // One more to also output 16:00
let minutesToAdd = 60;
let currentDate = new Date("2022-04-10 08:00:00");
for (let i = 0; i < timeDiff; i++) {
console.log(currentDate.toLocaleTimeString("en-SE", { timeStyle: "short" }));
currentDate.setMinutes(currentDate.getMinutes() + minutesToAdd);
}
You can then use a simple for-loop to iterate from 0 up to and including timeDiff, incrementing each iteration by 1.
for (let hours = 0; hours <= timeDiff; hours += 1) {
// ...
}
Instead of a starting date we'll start with a timestamp Date.parse("2022-04-10 08:00:00"). This allows us to add the time from the loop to the timestamp and create a new date.
const date = new Date(currentTimestamp + hours*HOURS);
To only display the time I've taken the liberty of using the solution provided by the answer of trincot.
const MILLISECOND = 1 , MILLISECONDS = MILLISECOND;
const SECOND = 1000*MILLISECONDS, SECONDS = SECOND ;
const MINUTE = 60*SECONDS , MINUTES = MINUTE ;
const HOUR = 60*MINUTES , HOURS = HOUR ;
const timeDiff = 8;
var currentTimestamp = Date.parse("2022-04-10 08:00:00");
for (let hours = 0; hours <= timeDiff; hours += 1) {
const date = new Date(currentTimestamp + hours*HOURS);
console.log(date.toLocaleString(undefined, { timeStyle: "short" }));
}

compare two dates by day in javascript

I'm trying to compare two dates by day in javascript. Comparing dates is fine, but I want just compare them by day and ignore the time of day. Is this possible without relying on a library like momentjs?
Here is a snippet that compares dates without time:
var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value);
d.setHours(0, 0, 0, 0);
if(d >= today){
alert(d is greater than or equal to current date);
}
And here is a function that will give you the exact difference between two days:
function daysBetween(first, second) {
// Copy date parts of the timestamps, discarding the time parts.
var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());
// Do the math.
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = two.getTime() - one.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
return Math.floor(days);
}

JavaScript, how to create difference of date with moment.js

I am having a problem with creating an error message on a page where there is a "from date:", and a "to date:". If the difference between the two dates is greater than or equal to 60 days, I have to put up an error message.
I am trying to use moment.js and this is what my code is looking like now. It was recommended that I use it in knockout validation code. this is what it looks like right now:
var greaterThan60 = (moment().subtract('days', 60) === true) ? "The max range for from/to date is 60 days." : null;
I am still not sure how to make it greater than 60 days, not just equal to 60 days. This is what my boss gave me to help.
Reference site for moment().subtract
moment.js provides a diff() method to find difference between dates. please check below example.
var fromDate = 20180606;
var toDate = 20180406;
var dif = moment(fromDate, 'YYYYMMDD').diff(moment(toDate, 'YYYYMMDD'),'days')
console.log(dif) // 61
subtract returns a new moment object. So checking for true always returns false. You can use range and diff to calculate a diff in days and check that:
let start = moment('2016-02-27');
let end = moment('2016-03-02');
let range = moment.range(start, end);
let days = range.diff('days');
let error = null;
if (days > 60) {
error = "The max range for from/to date is 60 days.";
}
You Can try this.
var date = Date.parse("2018-04-04 00:00:00");
var selectedFromDate = new Date(date);
var todayDate = new Date();
var timedifference = Math.abs(todayDate.getTime() - selectedFromDate.getTime());
var daysDifference = Math.ceil(timedifference/(1000 * 3600 * 24));
just use if else loop for greater than 60 days validation.
if(daysDifference > 60)
{
alert("From Date should be less than 2 months");
}
Use the .isSameOrAfter function to compare if the end value is greater than or equal to the start value plus sixty days. Example:
var greaterThan60 = toDate.isSameOrAfter(startDate.add(60, 'days'));
where toDate is your end time as a moment object and startDate is the start time as a moment object. If the end date is greater than or equal to 60 days after the start date, greaterThan60 will be true.
References:
isSameOrAfter
add

Check if a date is between two dates

I have an array with different dates with the format of year-month-day.
something like this:
var dates = ["2016-08-01", "2016-08-09", "2016-08-10", ....];
I also have a function that formats todays date in the same format as above. And is stored in a variable:
var currentDate; //Contains current date in the format of year-month-day
What i need to do is to check if any of the dates in the array, either:
Match with today's date.- e.g. Today would be 2016-08-13
Match with 14 days back from today's date. - e.g. 14 days back from today (2016-08-13) would be 2016-07-30
Or match with any dates between the current and 14 days back.
I'm trying to do this by looping through the array, checking each value. But im unsure about the if condition/conditions
for(var i = 0; i < dates.length; i++) {
if(currentDate === *condition*) {
sendDate(dates[i]);
}
}
Anyone have a good solution for this? Thanks in advance!
Firstly, create a new Date() from your currentDate ( currentDate is string format Y-d-m with hour and minutes is 00:00)
var current = new Date(currentDate);
var matchWithCurrent = [];
var matchWithDayBack = [];
var between = [];
just loop through your date array
for (var i=0; i<dates.length; i++) {
var tmpDate = new Date(dates[i]); //Convert string to date
var diff = Math.ceil((current - tmpDate) / (1000 * 3600 * 24)); //get time difference (current - tmpDate is milisecond, we need convert it to day)
// Check condition and push it on array correct
if (diff == 0) {
matchWithCurrent.push(dates[i]);
}
if (diff == 14) {
matchWithDayBack.push(dates[i]);
}
if ((diff > 0) && (diff <14)) {
between.push(dates[i]);
}
}
console.log(matchWithCurrent);
console.log(matchWithDayBack);
console.log(between);
If you want only one array match with 3 condition just check 3 condition in only one if and push it into your result array
One way would be to parse the dates to millisecond values and compare them.
var todayParts = currentDate.split('-');
var today = new Date(todayParts[0], todayParts[1], todayParts[2]).getTime();
var otherParts = dates[i].split('-');
var other = new Date(otherParts[0], otherParts[1], otherParts[2]).getTime();
if (today < other + 1209600000 /* 2 weeks in milliseconds */) {
// The other date is less than 2 weeks before today
}
You can read here why I parsed it manually instead of using Date.parse().
You can compare two dates something like that:
var currentDate = new Date();
for(var i = 0; i < dates.length; i++) {<br>
var arrDate = new Date(dates[i]);
if(currentDate == arrDate)
{//compare array dates with current date
//your code here
}
var beforeDate = (currentDate.getDate() - 14); //14 days before
if(arrDate >= beforeDate && arrDate <= currentDate){
//compare dates between current date and 14 days before date
}
}

Only show data on html page where javascript date is within last 10 days

I have javascript array in which the date coming in is in this format
2015-11-25T17:54:19.033
However, I am not really concerned with the time
so I end up with
11/25/15
What I want to do in my loop is to LOOK at the date ( either 2015-11-25T17:54:19.033 or 11/25/15 , whatever is easier) and just set a variable to "NEW" if it is within the last 10 days
I was attempted to play around with this code and it does not give me what I want at all
var dt = "11/25/15";
var today = new Date()
var priorDate = new Date().setDate(today.getDate()-10)
console.log(dt);
console.log(today);
console.log(priorDate);
pseudo code of what i WANT
if ( dt <= today ) {
x = "NEW";
}
So my thoughts are that it need to be in Date objects in javascript but i'm not sure
Update
So say in a loop i have these variables that occur
for ....
dt = 9/13/15
Output = 9/13/15
next time in loop
dt = 11/24/15
Output = NEW - 11/24/15
Working jsfiddle
http://jsfiddle.net/bthorn/yr009hwd/
You are correct. You need to convert the string date to a date time object in javascript to do the comparison.In order to do the comparison, you need to get the millisec of the dates using getTime()
var dt = new Date("11/22/2015");
var today = new Date();
if ( dt.getTime() < today.getTime() ) {
alert('Past');
}
else
alert('future');
To check if the date difference is within 10 days:
var dt = new Date("11/12/2015");
var today = new Date();
var dateDiffDays = Math.ceil((Math.ceil(dt.getTime() - today.getTime()))/(1000 * 3600 * 24));
if( dateDiffDays >= -10 && dateDiffDays <= 10)
alert('date within 10 days');
Depending on the format of your date string, you can probably just do:
var dateToTest = new Date(dt);
//get 10 days earlier
dateToTest.setDate(dateToTest.getDate() - 10);
var today = new Date();
if ( dateToTest < today ) {
x = 'NEW';
}
//see if a date is within the last 10 days
var tenDaysAgo = new Date(); //current date
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10); //ten days ago
//if you don't care about the time
tenDaysAgo.setHours(0);
tenDaysAgo.setMinutes(0);
tenDaysAgo.setSeconds(0);
tenDaysAgo.setMilliseconds(0);
var someDateToTest = new Date('11-1-2015');
if (tenDaysAgo > someDateToTest) {
//this is new
x = 'NEW';
}

Categories

Resources