Selecting a date between certain range based on conditions using groovy - groovy

I am having a little issue with a date generator code below. The list of the code below is to ensure that a random date is selected within the summer months (May, June, July August) for availability.
So what I did is that I say if the current month is less than 5 (less than May), then select a random date between 1st May this year till 31st August this year, else if the current month is past 7 (past July), then select a random date between 1st May next year till 31st August next year.
Now I notice a little glitch in my code I require help with. As I ran the code below today (8th May), it is possible that the date the random generator selects could be in May before today's date. Actually the issue is I don't have anything to handle when I am in the current months. So I think I require a little refactoring.
What i would like is that it checks the current date and if it between May to July (so not less than May or more than July), then check today's date and pick a date between today till the 31st August this year.
My brain has been fried and for some strange reason I am struggling on something which logically makes sense, but I've just been having issues programming it.
import groovy.time.TimeCategory
//def dataSet = testRunner.testCase.getTestStepByName("Properties")
// Select the current test data line
def dateFormat = 'yyyy-MM-dd'
def getNumberInRange = { min, max -> new Random().nextInt(max + 1 - min) + min }
def isTodayBeforeMay = { Calendar.MONTH < 5 }
def isTodayAfterJuly = { Calendar.MONTH > 7 }
//Get the number of days between today and given date
def getDifferenceDays = { targetDate, closure ->
def strDate = closure (targetDate)
def futureDate = new Date().parse(dateFormat, strDate)
TimeCategory.minus(futureDate, new Date()).days
}
//Get the offset between today and max date i.e.,31 august
def getOffSetDays = { date ->
//Need to change the date range if needed.
//As per OP, May to August is mentioned below
def max = getDifferenceDays(date) { "${it[Calendar.YEAR]}-08-31" }
def min = getDifferenceDays(date) { "${it[Calendar.YEAR]}-05-01" }
getNumberInRange(min, max)
}
def now = new Date()
def nextYearNow = now.updated(year: now[Calendar.YEAR] + 1)
def selected
def finalDate
log.info "Today : $now"
log.info "Next year same date : $nextYearNow"
if (isTodayBeforeMay()) {
selected = now
} else if (isTodayAfterJuly()) {
selected = nextYearNow
} else {
throw new Error("Not implemented for the days between 1st May to 30th July")
}
def offset = getOffSetDays(selected)
//Add the offset days to now
use(TimeCategory) {
finalDate = now + offset.days
}

All you need is to implement the else condition instead of throw new Error(..) below (code excerpt from the question):
If you read the code, it is crystal clear each condition and error message as place holder for the unknown data range in below and which is now you wanted it to be handled.
if (isTodayBeforeMay()) {
selected = now
} else if (isTodayAfterJuly()) {
selected = nextYearNow
} else {
throw new Error("Not implemented for the days between 1st May to 30th July")
}
Just add the below statement in the last else in place of threw new Error
selected = getOffSetDays(now)
EDIT:
You can try quickly online Demo
EDIT 2: Looks the above is not working at times randomly, so updating the answer:
import groovy.time.TimeCategory
def dateFormat = 'yyyy-MM-dd'
def getNumberInRange = { max, min = 1 -> new Random().nextInt(max + 1 - min) + min }
def isTodayBeforeMay = { Calendar.MONTH < 5 }
def isTodayAfterJune = { Calendar.MONTH > 6 }
//Get the number of days between today and given date
def getDifferenceDays = { targetDate, closure ->
def strDate = closure (targetDate)
def futureDate = new Date().parse(dateFormat, strDate)
TimeCategory.minus(futureDate, new Date()).days
}
def getPaddedString = { num, len = 2, padwith = '0' ->
num.toString().padLeft(len, padwith)
}
//Get the offset between today and max date i.e.,31 august
def getOffSetDays = { date, minMonth = 5, minDay = 1 ->
//Need to change the date range if needed.
//As per OP, May to August is mentioned below
def max = getDifferenceDays(date) { "${it[Calendar.YEAR]}-08-31" }
def min = getDifferenceDays(date) { "${it[Calendar.YEAR]}-${getPaddedString(minMonth)}-${getPaddedString(minDay)}" }
getNumberInRange(max, min)
}
def now = new Date()
def nextYearNow = now.updated(year: now[Calendar.YEAR] + 1)
def selected
def finalDate
println "Today : $now"
println "Next year same date : $nextYearNow"
if (isTodayBeforeMay()) {
selected = now
} else if (isTodayAfterJune()) {
selected = nextYearNow
}
def dayz = getNumberInRange(getDifferenceDays(now) { "${it[Calendar.YEAR]}-08-31" })
def offset = selected ? getOffSetDays(selected) : dayz
offset = offset > 0 ? offset : now[Calendar.DAY_OF_MONTH]+1
//Add the offset days to now
use(TimeCategory) {
finalDate = now + offset.days
}
println "Final future date is : $finalDate"
println "Final future date is(formatted) : ${finalDate.format(dateFormat)}"
assert now <= finalDate
This Demo generate the date 1000 times just to make sure the date is ok.

Related

Node JS: calculating number working in each month between a two dates

I am trying to develop a code to generate number of working days in each month between two selected dates:
Eg: Start Date is 20-Oct-2022 and End Date is 14-Feb-2023.
I am able to generate net working days between two dates, however not for each month between the two dates.
I am expecting the code to provide output as:
Net working days in
Oct'22 is 8,
Nov'22 is 21,
Jan'23 is 22 and
Feb'22 is 10.
var startDate = new Date('20/10/2022');
var endDate = new Date('14/02/2023');
var numOfDates = getBusinessDatesCount(startDate,endDate);
function getBusinessDatesCount(startDate, endDate) {
let count = 0;
const curDate = new Date(startDate.getTime());
while (curDate <= endDate) {
const dayOfWeek = curDate.getDay();
if(dayOfWeek !== 0 && dayOfWeek !== 6) count++;
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
like in above example you can calculate number of working days between two dates.

Split column into rows using excel office script

I would like to split a column into rows using excel office script but I cant figure out how.
I have a schedule in below format in excel which I would like to split into columns.
Original table
Final table need to be like this.
Final Table
Is this achievable, if yes, could someone please share the code
Based on your description I made an attempt at a solution with Office Scripts. It takes a table like this:
and outputs a new table on a new worksheet, like this:
For better or worse I attempted to keep the logic in the workbook via formulas derived from the first table and output into the second. This formula logic would need to be rewritten if there is more than one activity per day.
I'm not a developer but I can already see areas in this Office Script that need improvement:
function main(workbook: ExcelScript.Workbook) {
// delete new worksheet if it already exists so the rest of the script can run effectively
// should you need to retain data simply rename worksheet before running
if (workbook.getWorksheet("My New Sheet") != undefined) {
workbook.getWorksheet("My New Sheet").delete()
}
// assumes your original data is in a table
let myTable = workbook.getTable("Table1");
let tableData = myTable.getRangeBetweenHeaderAndTotal().getValues();
// extract the dates as excel serial numbers
let allDates:number[] = [];
for (let i = 0; i < tableData.length; i++) {
allDates.push(tableData[i][2], tableData[i][3]);
}
let oldestDate = Math.min(...allDates);
let newestDate = Math.max(...allDates);
let calendarSpread = newestDate-oldestDate+2;
// construct formula from the tableData
// first add a new 'column' to tableData to represent the days of the week (as numbers) on which the activity is planned. this will be an array added to each 'row'.
for (let r = 0; r < tableData.length; r++) {
tableData[r].push(findDay(tableData[r][1]));
}
// start a near blank formula string
let formulaText:string = '=';
// use the following cell reference
let cellRef = 'C2';
// construct the formual for each row in the data and with each day of the week for the row
let rowCount:number;
for (let r = 0; r < tableData.length; r++) {
if (tableData[r][4].length > 1) {
formulaText += 'IF(AND(OR(';
} else {
formulaText += 'IF(AND(';
}
for (let a=0; a < tableData[r][4].length; a++) {
formulaText += 'WEEKDAY(' + cellRef + ')=' + tableData[r][4][a].toString();
if (a == tableData[r][4].length - 1 && tableData[r][4].length > 1) {
formulaText += '),';
} else {
formulaText += ', ';
}
}
formulaText += cellRef + '>=' + tableData[r][2] + ', ' + cellRef + '<=' + tableData[r][3] + '), "' + tableData[r][0] + '", ';
rowCount = r+1;
}
formulaText += '"-"';
for (let p=0; p<rowCount; p++) {
formulaText += ')';
}
// create a new sheet
let newSheet = workbook.addWorksheet("My New Sheet");
// add the header row
let header = newSheet.getRange("A1:C1").setValues([["Activity", "Day", "Date"]])
// insert the oldest date into the first row, then add formula to adjacent cells in row
let firstDate = newSheet.getRange("C2")
firstDate.setValue(oldestDate);
firstDate.setNumberFormatLocal("m/d/yyyy");
firstDate.getOffsetRange(0, -1).setFormula("=C2");
firstDate.getOffsetRange(0, -1).setNumberFormatLocal("ddd");
firstDate.getOffsetRange(0, -2).setFormula(formulaText);
// use autofill to copy results down until the last day in the sequence
let autoFillRange = "A2:C" + (calendarSpread).toString();
firstDate.getResizedRange(0, -2).autoFill(autoFillRange, ExcelScript.AutoFillType.fillDefault);
// convert the the range to a table and format the columns
let outputTable = newSheet.addTable(newSheet.getUsedRange(), true);
outputTable.getRange().getFormat().autofitColumns();
//navigate to the new sheet
newSheet.activate();
}
// function to return days (as a number) for each day of week found in a string
function findDay(foo: string) {
// start with a list of days to search for
let daysOfWeek:string[] = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];
//create empty arrays
let searchResults:number[] = [];
let daysFound:number[] = [];
// search for each day of the week, this will create an array for each day of the week where the value is -1 if the day is not found or write the position where the day is found
for (let d of daysOfWeek) {
searchResults.push(foo.search(d));
}
// now take the search results array and if the number contained is greater than -1 add it's position+1 to a days found array. this should end up being a list of numbered days of the week found in a string/cell
for (let i = 0; i < searchResults.length; i++) {
if (searchResults[i] > -1) {
daysFound.push(i + 1);
}
}
return daysFound
}
I managed to get this working using below code for anyone who might be interested.
workbook.getWorksheet('UpdatedSheet')?.delete()
let usedRange = workbook.getActiveWorksheet().getTables()[0].getRangeBetweenHeaderAndTotal();
let newString: string[][] = [];
usedRange.getValues().forEach(row => {
let daysRows: string[][] = [];
let days = row[1].toString().split(',');
days.forEach(cellValue => {
if (cellValue != ' ') {
let eachDayData = row.toString().replace(row[1].toString(), cellValue).split(',');
daysRows.push(eachDayData);
}
});
daysRows.forEach(actualDay => {
const effDate = new Date(Math.round((actualDay[2] as unknown as number - 25569) * 86400 * 1000))
const disDate = new Date(Math.round((actualDay[3] as unknown as number - 25569) * 86400 * 1000))
getDatesInRange(effDate, disDate).forEach(element => {
let options = { weekday: 'short' }
if (element.toLocaleDateString('en-GB', options) == actualDay[1]) {
let datas = actualDay.toString().replace(actualDay[2], element.toDateString()).split(',')
datas.pop()
newString.push(datas)
}
});
});
});
workbook.getWorksheet('UpdatedSheet')?.delete()
let workSheet = workbook.addWorksheet('UpdatedSheet');
workSheet.activate();
let headers = workSheet.getRange('A1:C1').setValue([['Activity', 'Day', 'Date']])
let range = workSheet.getRange('A2');
let resizedRange = range.getAbsoluteResizedRange(newString.length, newString[0].length);
resizedRange.setValues(newString);
let tableRange = workSheet.getRange("A2").getSurroundingRegion().getAddress();
let newTable = workbook.addTable(workSheet.getRange(tableRange), true);
newTable.setName('updatedTable');
workSheet.getRange().getFormat().autofitColumns()
}
function getDatesInRange(startDate: { getTime: () => string | number | Date; }, endDate: string | number | Date) {
const date = new Date(startDate.getTime());
const dates: Date[] = [];
while (date <= endDate) {
dates.push(new Date(date));
date.setDate(date.getDate() + 1);
}
return dates;
}

How do I get the output of the function in Groovy

static def StartMonth() {
def date = new Date().format('MM')
def month = date.toInteger()
if (month > 6) {
month = month - 6
} else if (month <= 6) {
month = (month + 12) - 6
}
}
static void main(String[] args) {
StartMonth();
}
}
I have this and the output will be 4 (right now in October) and I want to retrieve that value so that I can have a new variable newDate = *startDate output* + '25/2019' but I do not know how to get the value back. (I am very new to this, I usually program in Javascript and even then I am still a beginner)
Thank you
In groovy you can return a value using the return value (as you can do in javascript). If there is no return a method returns the last value assigned (month in your case).
So you can either add return month in your StartMonth method. Or you can keep it as it is and just print it:
static void main(String[] args) {
println StartMonth()
}

Calendar.set error or infinite loop

the following does not seem to work, it seems to cause an infinite loop:
import java.text.SimpleDateFormat;
SimpleDateFormat out=new SimpleDateFormat('yyyy-MM-dd');
def from = Calendar.instance
from.set(year: 2017, month: Calendar.JANUARY, date: 3)
def to = Calendar.instance
to.set(year: 2017, month: Calendar.FEBRUARY, date: 3)
from.upto(to) {
cal=it;
prev=cal;
prev.set(Calendar.DAY_OF_MONTH, 1);
println out.format(prev.getTime());
}
can somebody please explain why this should not work? I don't get it. My goal is to get the first day of month within the upto loop.
Inside the loop, you are constantly setting the calendar back to the first day of the month...
It's similar to if you did:
for (int i = 0; i < 10; i++) {
i = 0
println i
}
(that will never finish either)
Also, you code will run for every day between the two dates... which I don't think is what you are looking for either
It's easier if you use immutable things over Calendar, and as you're on Java 8, you can do:
import java.time.*
import java.time.format.*
// Add a next method, so you can do ranges of LocalDates
LocalDate.metaClass.next = { delegate.plusDays(1) }
LocalDate from = LocalDate.of(2017, 1, 3)
LocalDate to = LocalDate.of(2017, 2, 3)
(from..to).each {
println it.format(DateTimeFormatter.ISO_DATE) + " : " + it.withDayOfMonth(1).format(DateTimeFormatter.ISO_DATE)
}

Linq-Entities: Fetch data excluding the overlapping data ranges, pick the largest period

I have 2 tables, Imports and Periods.
Imports has the following structure:
AdminID, PeriodID, Some more fields
1, 1
1, 2
1, 6
1, 50
Periods table has the following structure:
PeriodID, PeriodType, StartDate, EndDate, Description
1, 1, 2007-01-01, 2007-12-31, Year 2007
2, 2, 2007-01-01, 2007-03-31, Quarter 1 2007
3, 2, 2007-04-01, 2007-06-30, Quarter 2 2007
4, 2, 2007-07-01, 2007-09-30, Quarter 3 2007
5, 2, 2007-10-01, 2007-12-31, Quarter 4 2007
6, 3, 2007-01-01, 2007-01-31, January 2007
.
.
.
50, 2, 2011-01-01, 2011-03-31, Quarter 1 2011
Now, I need to build a linq query to fetch only the largest period(ignoring the smaller overlapping periods) based on the data in Imports table!
When I query for AdminID = 1, I should only get PeriodID = 1 & 50, ignoring/excluding the PeriodIDs 2 & 6 as they overlap in 1 and 50 as there is no overlapping data yet!
You, can the max help for picking the largest period and while retrieving the values by comparing the PeriodIDs in both tables right.
I'm not sure whether there is a convenient way to do this in the database, but when you pull the data locally, you can do in-memory LINQ queries, if this is appropriate. You need to do this in thee steps.
Step 1: Define a Range class that allows you to do comparisons on periods (see below).
Step 2: Pulling the periods from the database:
var ranges = (
from period in context.Periods
where period.Imports.Any(i => i.AdminID == adminId)
select new Range(period.StartDate, period.EndDate.AddDays(1)))
.ToArray();
Note the .ToArray() to pull everything locally.
Step 3: Aggregating / merging all the periods into a list of non-overlapping periods:
var mergedPeriods = (
from range in ranges
select ranges.Where(p => p.OverlapsWith(range))
.Aggregate((r1, r2) => r1.Merge(r2)))
.Distinct();
For this to work you need a specially designed Range type that contains OverlapsWith, Merge and Equals methods. It might look like this:
public class Range : IEquatable<Range>
{
public Range(DateTime start, DateTime exclusiveEnd)
{
if (exclusiveEnd < start)
throw new ArgumentException();
this.Start = start; this.End = exclusiveEnd;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public TimeSpan Duration { get { return this.End - this.Start; } }
public Range Merge(Range other)
{
if (!this.OverlapsWith(other)) throw new ArgumentException();
var start = this.Start < other.Start ? this.Start : other.Start;
var end = this.End > other.End ? this.End : other.End;
return new Range(start, end);
}
public bool Contains(Range other)
{
return this.Start <= other.Start && this.End > other.End;
}
public bool OverlapsWith(Range other)
{
return this.OverlapsOnStartWith(other) ||
other.OverlapsOnStartWith(this) ||
this.Contains(other) ||
other.Contains(this);
}
private bool OverlapsOnStartWith(Range other)
{
return this.Start >= other.Start && this.Start < other.End;
}
public bool Equals(Range other)
{
return this.Start == other.Start && this.End == other.End;
}
}
I hope this helps.
Well, after a long struggle, I did find an answer! With a single query to database!
And for everyone's benefit posting the same.
var oImportPeriods =
from o in Imports
where o.Administration.AdminID == 143
orderby o.Period.PeriodID
select o.Period;
var oIgnorePeriodList = (
from oPeriod in oImportPeriods
from oSearchPeriod in oImportPeriods
.Where(o => o.PeriodID != oPeriod.PeriodID)
where oPeriod.StartDate >= oSearchPeriod.StartDate
where oPeriod.EndDate <= oSearchPeriod.EndDate
select oPeriod.PeriodID)
.Distinct();
var oDeletablePeriods = oAdministrationPeriods
.Where(o => !oIgnorePeriodList.Contains(o.PeriodID));
foreach(var o in oDeletablePeriods)
Console.WriteLine(o.Name);

Resources