2

When I try the following:

Date now = Date.today();
String dayOfWeek = now.format('EEEE');
System.debug('****** now: ' + now + ' ' + dayOfWeek);

I get the following error:

Method does not exist or incorrect signature: [Date].format(String)

However when I write it like so:

Datetime now = Date.today();
String dayOfWeek = now.format('EEEE');
System.debug('****** now: ' + now + ' ' + dayOfWeek);

I get no error but the output is wrong (the day of week should be Wednesday):

|DEBUG|****** now: 2015-11-11 00:00:00 Tuesday

How can I get the correct dayOfWeek for the date, I want to use date because I do not need the time. I have verified that my timezone etc is correct in my salesforce settings. I want to stay away from odd 'hacks'

Any help would be greatly appreciated!

  • Try this: Datetime now = Date.today(); now = now.addHours(1); now.format('EEEE'); – Ashwani Nov 11 '15 at 17:24
  • @Ashwani That works but I was hoping to truncate the time all together because I need to compare two dates regardless of time, however you did answer the question so thank you very much for that. – Devnsyde Nov 11 '15 at 17:29
  • I have posted it as answer as well as reason. Perhaps it may help you. You can use DateTime.now(); – Ashwani Nov 11 '15 at 17:32
1

Try this:

Datetime now = Date.today(); 
now = now.addHours(1); 
now.format('EEEE');

Reason: You are type casting Date to DateTime. Date does not have Time component so formatting behave incorrectly.

  • You shouldn't be using Date.today() and then converting it to a DateTime. – sfdcfox Nov 11 '15 at 17:35
  • The code was just an example of the issue I am having, it isn't the exact code. Ashwani's answer solved my issue. I was trying to get the dayofweek for the first date in the month and it was giving me the incorrect day. Date beginningOfMonthDate = startDate.addMonths(i).toStartofMonth(); – Devnsyde Nov 11 '15 at 17:37
2

You're implicitly converting a DateTime from a Date; this ends up setting it to midnight GMT, which, for the Western hemispehere, results in the day being one day earlier when formatted for local time. Instead, use DateTime.now() to get the correct day:

DateTime now = DateTime.now();
String dayOfWeek = now.format('EEEE');
System.debug('****** now: ' + now + ' ' + dayOfWeek);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.