function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Aaron71Aaron71 

Convert date to date/time field

Hi,

 

I've been working on a trigger in which I attempt to convert a date field into a date/time field (with the time being 12:00:00 noon).  However I'm having a hard time getting the formatting correct.

 

The trigger runs on a custom Quote object.

The date field I'm trying to convert is named Required_Date__c.

The new date/time field is named Required_Date_Time__c.

I have also a text field named Test__c, which I use to check the string formatting. 

 

Here is the code snippet:

 

string Rhour = '12';

string Rminute = '00';

string Rsecond = '00';

string Rdate = String.valueOf(c.Required_Date__c) + ' ' + Rhour + ':' + Rminute + ':' + Rsecond;

c.Test__c = Rdate;

c.Required_Date_Time__c = datetime.valueOf(c.Test__c);

 

 

If I comment out the last line of the above snippet, the trigger runs fine and enters the string

2010-03-30 12:00:00

in the Test__c field.

However, when I try to deploy the trigger with the last line included, I get the following error: System.TypeException: Invalid date/time: null 12:00:00

 

I've tried many other things as well, but continue to bang my head against the wall.

 

Any help with this would be greatly appreciated.

 

Thanks!!

Aaron 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Tim__mTim__m

Hey Aaron,

 

First you should check the Required_Date__c is not null. Then you can assign Required_Date_Time__c using the newInstance methods of Datetime and Time...

 

if(c.Required_Date__c != null) { c.Required_Date_Time__c = Datetime.newInstance(c.Required_Date__c, Time.newInstance(12, 0, 0, 0)); }

 

 

 

All Answers

Tim__mTim__m

Hey Aaron,

 

First you should check the Required_Date__c is not null. Then you can assign Required_Date_Time__c using the newInstance methods of Datetime and Time...

 

if(c.Required_Date__c != null) { c.Required_Date_Time__c = Datetime.newInstance(c.Required_Date__c, Time.newInstance(12, 0, 0, 0)); }

 

 

 

This was selected as the best answer
Aaron71Aaron71

Thanks Tim, that worked like a charm.

 

It never occurred to me to check whether the Required_Date__c field was null, since this is a required field and would always contain a value.

 

Thanks again!

Aaron