[SalesForce] How to pass Date dynamically to newInstance method of Datetime

i want to pass date into newInstance method of datetime class then i will get date of week.when i have given static date it's working fine but when i try to pass dynamically i am getting error please share you ideas.

Working Part:

Datetime dt = DateTime.newInstance(2018, 9, 20);
String dayOfWeek=dt.format('EEEE');
System.debug('Day : ' + dayOfWeek);

Not working Part:

i am getting dates from external system so i can't assign statically here i am facing problem

String s1 = '2018-09-21';
String target = '-';
String replacement = ',';
String s2 = s1.replace(target, replacement);
Datetime dt = DateTime.newInstance(s2);
String dayOfWeek=dt.format('EEEE');
System.debug('Day : ' + dayOfWeek);

Best Answer

DateTime.newInstance() does not accept a String as its parameter. You will need to parse the incoming string to create a DateTime value. There are (at least) three approaches to this:

  • Write your own code to parse the incoming date format into components (month, day, year) and pass them to DateTime.newInstance() yourself.
  • Use the DateTime.parse() method, which does accept a string. However, it's important to note that this method

Constructs a Datetime from the given String in the local time zone and in the format of the user locale.

For that reason, if you cannot ensure this code runs in a user context with a specific locale that matches the date format of your incoming data, you should not use it, and its fragility suggests it's a poor solution overall.

  • User the DateTime.valueOf() method, or deserialize JSON into a class with a DateTime member variable. In both cases, the incoming Date[time] string should be in ISO format: yyyy-MM-dd HH:mm:ss.
Related Topic