[SalesForce] how to get the date and time format that you want in apex

I have these lines of codes in my test class:

Test.startTest();        
    String sch = '0 0 23 * * ?';         
    String jobId = System.schedule('Delete Batch Donation Logs', sch, batchDeleteLogs);
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; 
    System.assertEquals(0, ct.TimesTriggered); 
    System.assertEquals(date.today()+' '+ '23:00:00', String.valueOf(ct.NextFireTime));
    Test.stopTest();

the date format that I need is the year-month-day only (2018-07-25) without time. how can I achieve that?

Best Answer

You can use the format method of the DateTime Class. It outputs the date in the desired format.

Example:

System.now().format('yyyy-MM-dd')

Optionally, for you example, you can compare actual DateTimes without converting to string

System.assertEquals(DateTime.newInstance(System.today(), Time.newInstance(23, 0, 0 , 0)), ct.NextFireTime);
Related Topic