function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Harsh P.Harsh P. 

Compare createdDate with todays Date

Hi All,

I want to compare createdDate with todays Date.
I have tried this one: 
 
List<contact> con = [Select Id,LastName,Owner.Email,OwnerId,CreatedDate,Email from Contact];
for(contact c : con) {
    if(c.CreatedDate == system.now()){
        system.debug('if');
    }else{
        system.debug('else');
    }
}


It is printed else .I want to get IF part.
Help to get the way...............
Thanks in Advance..............! 

Best Answer chosen by Harsh P.
Harsh P.Harsh P.
Thanks Rajeshwari........!
I have find solution for this.
First we need to take date conversion of both and then use boolean function like this[boolean cmpdt = todayDate_instance.isSameDay(createdDateField_instance);]
List<contact> con = [Select Id,LastName,Owner.Email,OwnerId,CreatedDate,Email from Contact];
  Date d =System.Today();
    system.debug(d);

for(contact c : con) {

    date convCD =c.CreatedDate.date();
    system.debug(convCD);
    boolean cmpdt = d.isSameDay(convCD);

    if(cmpdt == true){
        system.debug('if');
    }else{
        system.debug('else');
    }
}

Regards,
Harsh P.
 

All Answers

Raji MRaji M
Hi Harsh,
Created Date and System.Now() are DateTime Stamps. Contacts would have created in past and System.Now will never be equal to contacts created data as it may differ in seconds also. 
You need to convert to DateTime to Date format and compare.

Corrected your code-

List<contact> con = [Select Id,LastName,Owner.Email,OwnerId,CreatedDate,Email from Contact];
for(contact c : con) {
    if(c.CreatedDate.date() == system.Today()){
        system.debug('if');
    }else{
        system.debug('else');
    }
}

Thanks,
Raji M
Harsh P.Harsh P.
Hi Rajeshwari,

Thanks for the helpful reply but it also not execute IF statement.
Harsh P.Harsh P.
Thanks Rajeshwari........!
I have find solution for this.
First we need to take date conversion of both and then use boolean function like this[boolean cmpdt = todayDate_instance.isSameDay(createdDateField_instance);]
List<contact> con = [Select Id,LastName,Owner.Email,OwnerId,CreatedDate,Email from Contact];
  Date d =System.Today();
    system.debug(d);

for(contact c : con) {

    date convCD =c.CreatedDate.date();
    system.debug(convCD);
    boolean cmpdt = d.isSameDay(convCD);

    if(cmpdt == true){
        system.debug('if');
    }else{
        system.debug('else');
    }
}

Regards,
Harsh P.
 
This was selected as the best answer