Salesforce Apex how to convert string to datetime
•9 min read
In Salesforce Apex, you can easily convert a String to a DateTime using the built-in method DateTime.valueOf(string).
Here’s a full explanation with working code examples 👇
✅ 1. Basic Conversion Example
String dateTimeString = '2025-11-08 14:30:00';
DateTime myDateTime = DateTime.valueOf(dateTimeString);
System.debug('Converted DateTime: ' + myDateTime);
JavaScript🧠 Explanation:
- The string must be in the format:
yyyy-MM-dd HH:mm:ss - Example:
"2025-11-08 14:30:00" - Output:
2025-11-08 14:30:00
✅ 2. If the String Contains a "T" (ISO 8601 Format)
Sometimes, Salesforce returns DateTime as 2025-11-08T14:30:00.000Z (with T and Z).
You can handle that like this:
String isoDateTimeString = '2025-11-08T14:30:00.000Z';
DateTime myDateTime = DateTime.valueOfGmt(isoDateTimeString);
System.debug('Converted DateTime (GMT): ' + myDateTime);
JavaScript🧠 Note:
- Use
DateTime.valueOfGmt()if your time string ends withZ(UTC timezone).
✅ 3. If You Have Separate Date and Time Strings
String dateString = '2025-11-08';
String timeString = '14:45:30';
Date myDate = Date.valueOf(dateString);
Time myTime = Time.valueOf(timeString);
DateTime myDateTime = DateTime.newInstance(myDate, myTime);
System.debug('Combined DateTime: ' + myDateTime);
JavaScript✅ 4. With Error Handling (Safe Conversion)
To avoid runtime exceptions if the string format is wrong:
String inputString = '2025-11-08 10:00:00';
DateTime parsedDateTime;
try {
parsedDateTime = DateTime.valueOf(inputString);
System.debug('Valid DateTime: ' + parsedDateTime);
} catch (Exception e) {
System.debug('Invalid DateTime format: ' + e.getMessage());
}
JavaScript⚙️ Common String Formats Salesforce Supports
| Format Type | Example | Conversion Method |
|---|---|---|
yyyy-MM-dd HH:mm:ss | 2025-11-08 14:30:00 | DateTime.valueOf() |
yyyy-MM-dd'T'HH:mm:ss.SSS'Z' | 2025-11-08T14:30:00.000Z | DateTime.valueOfGmt() |
| Separate date & time | '2025-11-08', '14:30:00' | DateTime.newInstance(Date, Time) |
Related Posts

How to Automatically create a follow-up Task when a Lead is converted

How You need to update a related child record whenever a parent record’s status changes, but only if the status is “Closed Won.” How would you design this in Apex?
