Code to get previous weekday

I have a date variable and I need a custom java script to compute the previous weekday e.g.

  • if the date is Mon 06 Jan 2020, the previous weekday should be Friday 03 Jan 2020.
  • If the date is Fri 03 Jan 2020, the previous weekday should be Thu 02 Jan 2020.

Can anyone help ? Thanks

HI @gancw,
Try this ,This might help you

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://web-harvest.sourceforge.net/schema/1.0/config" scriptlang="groovy">
<script>
import java.time.LocalDateTime;

LocalDateTime date = LocalDateTime.now();
String current_day =date.getDayOfWeek()
println current_day
String day;
if(current_day.equals("TUESDAY")||current_day.equals("WEDNESDAY")||current_day.equals("THURSDAY")||current_day.equals("FRIDAY"))
         {
            date = date.minusDays(1);
 				println date
 				day =date.getDayOfWeek()
 				println day
 		 }  
         if(current_day.equals("MONDAY"))
          {
 		 date = date.minusDays(3);
 		 day=date.getDayOfWeek()
 		 println date
 		 prinltn day
		}
	
               </script>

    <export include-original-data="true"></export>

</config>

If you are happy with this.Please mark this as solution ,this might help others as well

1 Like

ravikumar177,
Thanks for the quick reply. I converted the code to Groovy Script format and put it inside a Custom Action but get an error when running the code.
date1 and date2 are datetime Recorder variables.

import java.time.LocalDateTime;
@CustomScriptAction(
        input = ['date1'],
        output = 'date2' 
	)

def PrevWorkDay() {

String day =date1.getDayOfWeek();

if(day.equals("MONDAY"))
{
	date2 = date1.minusDays(3);
}
else
{
	date2 = date1.minusDays(1);
}  

}

I have managed to get it working using the following Groovy code :

@CustomScriptAction(
    input = ['date1'],
    output = 'date2'
)
def customeScript() {
    int dow = date1.getDayOfWeek().getValue();
    if (dow==1)
    {
    date2 = date1.minus(java.time.Period.ofDays(3))
    }
    else
    {
    date2 = date1.minus(java.time.Period.ofDays(1))
    }
}
2 Likes