0

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);
2

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.
2

There is no newinstance method that accepts string and create the DateTime Instance. You can use string manipulation to your advantage.

 String s1 = '2018-09-21';
    List<String> dateStringList =s1.split('-');
    Datetime dt = DateTime.newInstance(Integer.valueOf(dateStringList[0]),Integer.valueOf(dateStringList[1]),Integer.valueOf(dateStringList[2]));
    String dayOfWeek=dt.format('EEEE');
    System.debug('Day : ' + dayOfWeek); //Prints Friday

This way, you dont have to worry about user locale.

SRC: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm

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.