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!

3
  • Try this: Datetime now = Date.today(); now = now.addHours(1); now.format('EEEE');
    – Ashwani
    Nov 11, 2015 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, 2015 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, 2015 at 17:32

2 Answers 2

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.

2
  • You shouldn't be using Date.today() and then converting it to a DateTime.
    – sfdcfox
    Nov 11, 2015 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, 2015 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);
1
  • I am iterating over the datetime using while loop, and adding the day by one which then gives me date with time 00:00:00 currentGMTDateTime = currentGMTDateTime.addDays(1); Now for the second datetime when I have the above snippet it still gives me a day before value. Ex if its Sunday today, the code prints Saturday Jul 30, 2023 at 19:58

You must log in to answer this question.

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