3

I'm programming a batch that needs to mail community users if they've created their user exactly account 39 days ago.

It seems difficult to query on a specific day ... I first tried :

Date limitDay = Date.today().addDays(-CONST_39D_SINCE_INITIAL_MESSAGE);

And in the SOQL clause

WHERE CreatedDate = :limitDay

It didn't work. Then I understood it was because CreatedDate is a DateTime, not a Date, and it was source of issues ;

This seems to work, but I'm not sure it's beautiful coding...

    public static void testDates () {
    Integer n = 0;

    Date d = System.today().addDays(n); // IsPortalEnabled
    Date d2 = System.today().addDays(n+1);

    System.debug('d : '+d+'\nd2 : '+d2);
    List<User> uList = [SELECT Id, CreatedDate FROM User WHERE CreatedDate >=:d AND CreatedDate <= :d2];

    // debug
    if(!uList.isEmpty()) {
        //System.debug(String.join(uList, '\nUser : '));
        for(User u : uList) {

            System.debug('User : '+ u + '\n                            Créé le : '+u.CreatedDate);
        }
    } else {
        System.debug('Got no User');
    }
}
1
  • Another thing is, do I only have to update the isActive field, or also IsPortalEnabled ? I just noticed the second one .. Feb 25, 2020 at 14:18

2 Answers 2

4

The comparison you want to make is possible with the DAY_ONLY function

[SELECT Id FROM User WHERE DAY_ONLY(createddate) = :Date.today().adddays(-39)];

You might also be-able to do what you want without a batch class but with for instance a process builder. That would save you writing a batch class.

1
  • Nice !! This works perfectly, thanks ! ... About the PB, it's a shame. I should think more Business Analyst... Feb 25, 2020 at 16:06
2

you can use date formats and literals in the query:

List<User> userList = [SELECT name, CreatedDate FROM User WHERE DAY_ONLY(CreatedDate) = :system.today().addDays(-39)];;

    if(!userList.isEmpty()) {

        for(user userObj: userList) {
            //your code here
        }
    }

The above code should do the trick.

hope this helps!!

6
  • THanks for the idea but it's not working, you can test with inspector, it brings back users created on the last 39 days :( Feb 25, 2020 at 16:02
  • yeah wasn't that the case? do you need user who were created before 39 days?? above query returns users who were created in the last 39 days
    – Abhijith E
    Feb 25, 2020 at 16:04
  • My bad, I've written again the more exact fact in introduction, I admit it wasnt clear : I need to bring users that created their account exactly 39 days ago ! That changes the issue - thanks and sorry ! Feb 25, 2020 at 16:08
  • 1
    Updated the code!! as per the description also tested it 😀
    – Abhijith E
    Feb 25, 2020 at 16:15
  • Yes !! Thanks, this works, I wasn't aware of the DAY_ONLY() function... Usefull tool ! Nice thanks ;) Feb 25, 2020 at 16:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .