Converting Date to DateTime

  • Added due date on case which is a date field. Trying to get this as dateTime and here is my code:

    case c = [select id, caseNumber, Due_Date__c, status, type from case limit 1];
    Date i = (c.Due_Date__c);
    system.debug(i);// returns 2015-08-07 00:00:00
    DateTime t = dateTime.newInstance(i, '11:59:59');
    //DateTime t = DateTime.parse(i, 11, 59, 59);
    //DateTime Dt = DateTime.newInstance(i, 11, 59, 59);
    system.debug(t);
    

    Getting Error: "Variable does not exist: datetime"

    Update: crmprogdev solution below works perfectly. I found another solution for the same using time.newinstance.

    case c = [select id, due_date__c from case where due_date__C != null limit 1];               
    date d = c.due_date__C;
    system.debug(d);
    DateTime dt = datetime.newInstance(d, Time.newInstance(23,59,59,59));
    system.debug(dt);
    

    You are receiving this error because you have the wrong signature for dateTime.newInstance. See this reference. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm#apex_System_Datetime_newInstance_2

    @Berg, Date i won't return the 11:59:59. If he wants that, he'll need to specify it when he creates the new datetime instance.

  • crmprogdev

    crmprogdev Correct answer

    6 years ago

    I think the simplest method for you to use will be something like the following:

    Integer d = Due_Date__c.day();
    Integer mo = Due_Date__c.month();
    Integer yr = Due_Date__c.year();
    
    DateTime DT = DateTime.newInstance(yr, mo, d);
    

    If you want to keep the 11:59:59 in your local time zone, change the last line as follows:

    DateTime DT = DateTime.newInstance(yr, mo, d, 11, 59, 59);
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used