+ Start a Discussion
DManelskiDManelski 

In a trigger, how do I set a date to next Tuesday?

I know how to perform this function using a formula in a workflow rule:

Code:
CASE( MOD(  TODAY()  - DATE(1900, 1, 7), 7),

2, TODAY(),

3, TODAY()+6,

4, TODAY()+5,

5, TODAY()+4,

6, TODAY()+3,

0, TODAY()+2,

1, TODAY()+1,

TODAY() )


How do I do this very same thing in an Apex trigger?

I tried this, and it set the date to Tuesday of this week:
Code:
Email_Series_Start_Date__c = System.today().toStartOfWeek()+2;    

However, I'd really like to set it to the next Tuesday if Tuesday has already passed this week. As an aside, this date field is driving the start date for an email drip campaign which should send on Tuesdays.
 
Thanks in advance.

Dave M.


Message Edited by DManelski on 10-22-2008 03:54 PM
jeremy_rossjeremy_ross
Code:
nextTuesday = Date.today().toStartOfWeek()+2; 
if (nextTuesday < Date.today()) {
nextTuesday = nextTuesday.addDays(7);
}

 Try adding the if statement above.  Seems to work.

Jeremy
jrotensteinjrotenstein
How about this?
Code:
Email_Series_Start_Date__c = System.today().addDays(-3).toStartOfWeek().addDays(9);

 It takes the date back two days, shortens it to the start of the (shifted) week, then adds a week plus the original two days.

eg
Sunday 8th returns Tuesday 10th
Monday 9th returns Tuesday 10th
Tuesday 10th returns Tuesday 10th
Wednesday 11th through Tuesday 17 returns Tuesday 17th

Neat, eh!


Message Edited by jrotenstein on 10-23-2008 03:52 PM
DManelskiDManelski
Brilliant, thanks John and Jeremy.

I'm going to go with John's solution since it's a little less code and doesn't require me to create a new variable but both work great.

Many thanks!

Dave
jeremy_rossjeremy_ross
jrotenstein,

That's more elegant.  But it looks like Tuesday the 17th would return Tuesday the 25th if Sunday is start of week.