2

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?

2 Answers 2

1

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);
3
  • Are you sure about your example? As there is no format method available in Date class which accepts argument String.
    – Saroj Bera
    Jul 24, 2018 at 10:26
  • You're right @SarojBera, I'll edit the response Jul 24, 2018 at 14:41
  • System.assertEquals(DateTime.newInstance(System.today(), Time.newInstance(23, 0, 0 , 0)), ct.NextFireTime) works for me... thank you
    – Mae
    Jul 25, 2018 at 1:44
1

You can do like this.

Option1

Date dToday = System.Today();
String yr = String.valueOf(dToday.year());
String mt = String.valueOf(dToday.month());
if(mt.length()==1){
    mt = '0'+mt;
}
String dt = String.valueOf(dToday.day());
if(dt.length()==1){
    dt = '0'+dt;
}                
String nextDate = yr+'-'+mt+'-'+dt;
System.debug('startdate : '+nextDate);

Option2

String dateFormat = 'yyyy-MM-dd';
DateTime dt = DateTime.now();
String dateString = dt.format(dateFormat);
System.debug(dateString);

You must log in to answer this question.

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