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
OpsterOpster 

Convert String containing date time to a DateTime in APEX

I have a String dtme = "July 1, 2009 10:00 AM".   I need to convert it to a DateTime in APEX.   Would someone be able to show me the code to do this properly?

 

any help is much appreciated.

 

thanks

Best Answer chosen by Admin (Salesforce Developers) 
bbrantly1bbrantly1

I should have noted even though my code coverts the string to a DateTime Var that my function returns a string

 

 

public string getConvertDateTime()

 

The Return Function

 

 

return myDate.format();

 

To use my code in the way you are you'll need to modify the function type to DateTime and have the function just return a DateTime not a String.

 

You can use the code below:

 

 

public DateTime getConvertDateTime(string strDT)
{

Map<string,integer> MapMonthList = new Map<string,integer>();
MapMonthList.put('January',1);
MapMonthList.put('February',2);
MapMonthList.put('March',3);
MapMonthList.put('April',4);
MapMonthList.put('May',5);
MapMonthList.put('June',6);
MapMonthList.put('July',7);
MapMonthList.put('August',8);
MapMonthList.put('September',9);
MapMonthList.put('October',10);
MapMonthList.put('November',11);
MapMonthList.put('December',12);

String[] strDTDivided = strDT.split(' ');

string month = String.ValueOf(MapMonthList.get(strDTDivided.get(0)));
string day = strDTDivided.get(1).replace(',', '');
string year = strDTDivided.get(2);

string hour = strDTDivided.get(3).split(':').get(0);
string minute = strDTDivided.get(3).split(':').get(1);
string second = '00';

if (strDTDivided.get(4) == 'PM')
{
hour = String.ValueOf(Integer.ValueOf(hour) + 12);
}
string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;

return datetime.valueOf(stringDate);

}

 

 

You will call the function like:

 

 

Datetime dtme = getConvertDateTime(dt);

 

Since the function outputs a DateTime now you don't need to recall the ValueOf function.

 

 

 

 

 

 

 

Message Edited by bbrantly1 on 06-30-2009 06:36 PM

All Answers

AlsoDougAlsoDoug

Here is a quick paste of some code I use to do it.

 

From what I can tell the only way in Apex to see if a string is a valid date it to try to make it a date and if it throws an exception it's not a date.

 

 

try{ task.reminderDateTime = datetime.valueOf(reminderDatetimeString); } catch (Exception e){ task.reminderDateTime = null; }

 

 

 

OpsterOpster

Yes I can see that your code would work if my string were correctly formatted.   However, I get an error:

 

System.TypeException: Invalid date/time: July 1, 2009 10:00 AM  

Any other ideas?

AlsoDougAlsoDoug

I formatted my date in javascript to get it into the format Apex likes (not sure if this was lazy or brilliant of me) but I know it was a pain in the butt to get working at the time (but I have reused it several times since then).

 

I am using Ext Js library and fields etc for my dateTime on front end but I think the below this is all standard java script stuff (in otherwords is 5something pm and I didn't do any testing)

 

 

var newDate = new Date(newValue);
var dateInFormat = newDate.format("Y-m-d H:i:s");
document.getElementById('{!hiddenFieldIdToUpdate}').value = dateInFormat;

 

so when the user blurs the date field I run the above taking the way they input the data, formatting it to the way salesforce should like it, and then stick it in a field that the Apex code (posted before) looks at.

 

 

 Hope that helps.

 

Doug

 

bbrantly1bbrantly1

Here is some code that will format the date you gave in the correct formate for DateTime.ValueOf(string) to work

 

 

public string getConvertDateTime() { string strDT = 'July 1, 2009 10:00 PM'; Map<string,integer> MapMonthList = new Map<string,integer>(); MapMonthList.put('January',1); MapMonthList.put('February',2); MapMonthList.put('March',3); MapMonthList.put('April',4); MapMonthList.put('May',5); MapMonthList.put('June',6); MapMonthList.put('July',7); MapMonthList.put('August',8); MapMonthList.put('September',9); MapMonthList.put('October',10); MapMonthList.put('November',11); MapMonthList.put('December',12); String[] strDTDivided = strDT.split(' '); string month = String.ValueOf(MapMonthList.get(strDTDivided.get(0))); string day = strDTDivided.get(1).replace(',', ''); string year = strDTDivided.get(2); string hour = strDTDivided.get(3).split(':').get(0); string minute = strDTDivided.get(3).split(':').get(1); string second = '00'; if (strDTDivided.get(4) == 'PM') { hour = String.ValueOf(Integer.ValueOf(hour) + 12); } string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; Datetime myDate = datetime.valueOf(stringDate); return myDate.format(); }

 A couple of key points:

1.) Salesforce uses a 24 hour clock so you have to check to see if your date includes PM - if so you add 12 hours.

2.) This code will only work the format you provided

 

When I run this code I get "7/1/2009 10:00 PM"

 

Hope this helps!

 

OpsterOpster

That code sample is looking great, but I still get an error when I call DateTime.ValueOf

 

System.TypeException: Invalid date/time: 7/1/2009 10:00 AM

 

 

bbrantly1bbrantly1
Can you post the code which is giving you the DateTime value you are trying to convert?
bbrantly1bbrantly1

Here is some code I just wrote that will convert a date in either one of the below formats to a DateTime var.

 

Formats:

8/1/2009 10:00 PM

July 1, 2009 10:00 PM

 

Code:

 

public string getConvertDateTime() { //string strDT = '8/1/2009 10:00 PM'; string strDT = 'July 1, 2009 10:00 PM'; //Place Date String Here if (strDT.contains('/')) { String[] strDTDivided = strDT.split(' '); String[] DDate = strDTDivided.get(0).split('/'); String TTime = strDTDivided.get(1); string month = DDate.get(0); string day = DDate.get(1); string year = DDate.get(2); string hour = TTime.split(':').get(0); string minute = TTime.split(':').get(1); string second = '00'; if (strDTDivided.get(2) == 'PM') { hour = String.ValueOf(Integer.ValueOf(hour) + 12); } string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; Datetime myDate = datetime.valueOf(stringDate); return myDate.format(); } else if (strDT.contains(',')) { Map<string,integer> MapMonthList = new Map<string,integer>(); MapMonthList.put('January',1); MapMonthList.put('February',2); MapMonthList.put('March',3); MapMonthList.put('April',4); MapMonthList.put('May',5); MapMonthList.put('June',6); MapMonthList.put('July',7); MapMonthList.put('August',8); MapMonthList.put('September',9); MapMonthList.put('October',10); MapMonthList.put('November',11); MapMonthList.put('December',12); String[] strDTDivided = strDT.split(' '); string month = String.ValueOf(MapMonthList.get(strDTDivided.get(0))); string day = strDTDivided.get(1).replace(',', ''); string year = strDTDivided.get(2); string hour = strDTDivided.get(3).split(':').get(0); string minute = strDTDivided.get(3).split(':').get(1); string second = '00'; if (strDTDivided.get(4) == 'PM') { hour = String.ValueOf(Integer.ValueOf(hour) + 12); } string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; Datetime myDate = datetime.valueOf(stringDate); return myDate.format(); } else { return 'No Conversion Method'; } }

 

If you provide your code that is returning your date string i'll be happy to provide you with some suggestions/code on how you can always convert it to a DateTime var 100% of the time.

OpsterOpster

I am using the code you posted :)

 

String dt = 'July 1, 2009 10:00 PM';

 

Datetime dtme = DateTime.ValueOf(getConvertDateTime(dt));

 

 

 

public string getConvertDateTime(string strDT)

{

//string strDT = 'July 1, 2009 10:00 PM';

 

Map<string,integer> MapMonthList = new Map<string,integer>();

MapMonthList.put('January',1);MapMonthList.put(

'February',2);

MapMonthList.put('March',3);MapMonthList.put(

'April',4);

MapMonthList.put('May',5);MapMonthList.put(

'June',6);

MapMonthList.put('July',7);MapMonthList.put(

'August',8);

MapMonthList.put('September',9);MapMonthList.put(

'October',10);

MapMonthList.put('November',11);MapMonthList.put(

'December',12);

 

String[] strDTDivided = strDT.split(' ');

 

string month = String.ValueOf(MapMonthList.get(strDTDivided.get(0)));

string day = strDTDivided.get(1).replace(',', '');

string year = strDTDivided.get(2);

 

string hour = strDTDivided.get(3).split(':').get(0);

string minute = strDTDivided.get(3).split(':').get(1);string second =

'00';

 

if (strDTDivided.get(4) == 'PM')

{

hour = String.ValueOf(Integer.ValueOf(hour) + 12);

}

string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;

 

Datetime myDate = datetime.valueOf(stringDate);

 

return myDate.format();

 

}

OpsterOpster
even with the new code posted I get the same error.   So something odd is still happening
bbrantly1bbrantly1

I should have noted even though my code coverts the string to a DateTime Var that my function returns a string

 

 

public string getConvertDateTime()

 

The Return Function

 

 

return myDate.format();

 

To use my code in the way you are you'll need to modify the function type to DateTime and have the function just return a DateTime not a String.

 

You can use the code below:

 

 

public DateTime getConvertDateTime(string strDT)
{

Map<string,integer> MapMonthList = new Map<string,integer>();
MapMonthList.put('January',1);
MapMonthList.put('February',2);
MapMonthList.put('March',3);
MapMonthList.put('April',4);
MapMonthList.put('May',5);
MapMonthList.put('June',6);
MapMonthList.put('July',7);
MapMonthList.put('August',8);
MapMonthList.put('September',9);
MapMonthList.put('October',10);
MapMonthList.put('November',11);
MapMonthList.put('December',12);

String[] strDTDivided = strDT.split(' ');

string month = String.ValueOf(MapMonthList.get(strDTDivided.get(0)));
string day = strDTDivided.get(1).replace(',', '');
string year = strDTDivided.get(2);

string hour = strDTDivided.get(3).split(':').get(0);
string minute = strDTDivided.get(3).split(':').get(1);
string second = '00';

if (strDTDivided.get(4) == 'PM')
{
hour = String.ValueOf(Integer.ValueOf(hour) + 12);
}
string stringDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;

return datetime.valueOf(stringDate);

}

 

 

You will call the function like:

 

 

Datetime dtme = getConvertDateTime(dt);

 

Since the function outputs a DateTime now you don't need to recall the ValueOf function.

 

 

 

 

 

 

 

Message Edited by bbrantly1 on 06-30-2009 06:36 PM
This was selected as the best answer
OpsterOpster

Of course!   Sorry for my lapse of conciousness.

 

It works great now.   Thank You

bbrantly1bbrantly1

No problem!  Now people have two functions to convert two different strings to DateTime Vars.

 

Feel free to email me directly bbrantly@sabersolutions.com if you have futher problems in development

Lakshmi MLakshmi M

Hi Friends,

All these above date conversion methods were useful.

But if we have the time as 12 PM,the result would be 24. then it goes to end of the day/midnight. So this could be a problem as per my understanding.

Thank you.

 

Regards,

Lakshmi

ClarkBransonClarkBranson

Good catch, I would suggest adding something like this, anyone else have comments?

 

 

if (strDTDivided.get(4) == 'PM'&& hour != '12')
{
hour = String.ValueOf(Integer.ValueOf(hour) + 12);
}
Lakshmi MLakshmi M

Yes absolutely,

The same way, i have done.

If(strDTDivided.get(4) == 'PM'&& hour < '12')

{

          hour = String.ValueOf(Integer.ValueOf(hour) + 12);

}

Thank you.

 

Regards,

Lakshmi M.

Lakshmi MLakshmi M

Also if the time is 12 AM the12 has to be reduced from the time in else condition then the code will work properly at any time.

 

Thank you.

Regards,

Lakshmi

Mayank_JoshiMayank_Joshi

Another handy Approach ,which might be useful for converting DateTime to String :

 

Sales_Request__c ResponseList = Lst_Response[0];  // iterating using List 

 

Datetime ResponseDATE = ResponseList.Sales_Request_Date__c;
String Response_Request_Received = ResponseDATE.format('MM/dd/yyyy HH:mm:ss');

 

System.debug('STRING TEST :'+ Response_Request_Received);

Manisha GuptaManisha Gupta

How can I achieve the same funcionality in formula?

Mayank_JoshiMayank_Joshi
You have use Formula field with Date/Time Data Type and pass the Date Time Field (Api Name) into that .

But , Formula field are read only ,if you want to modify it .

Thanks
rajesh k 10rajesh k 10
Hi Mayank,
How to convert String(Tue Nov 18 00:00:00 GMT 2014) to Date(11/18/2014)?,
       I have Two Strings Like
String s1='Tue Nov 18 00:00:00 GMT 2014';
String s2='Sun Nov 30 00:00:00 GMT 2014';

How To get s1 and s2 are like below
o/p:Date s1=11/18/2014
      Date s2=11/30/2014

help me...
Aniruddha ManakeshwarAniruddha Manakeshwar
Hi All,

Does anyone has written any piece of code which accepts Date/Datetime in any format and convert it into the desired output format provided? What I see the above code will only work MMMM DD, YYYY format, What about other formats like  'MMMM d, yyyy' , 'MMMMM dd, yyyy',  'MMMMM dd, yy', 'MMMMM d, yy', 'MMM d, yyyy', 'MMM dd, yyyy', 'MMM dd, yy', 'MMM d, yy''MM d, yyyy', 'MM dd, yyyy' , 'MM dd, yy', 'MM d, yy'.
There might be a lot of different formats, what I am trying to achieve here is to make it more dynamic. I have written following code so far, but unable to achieve the desired result. Appreciate for your help !!!

public String formatDateTime(String srcDateTime, String inputMask, String outputMask){
        Datetime resultDateTime;
        Date parsedDate;    
        Map<String, Integer> monthMap = new Map<String,Integer> 
                {'january' => 1, 'febuary' =>2 , 'march' => 3, 'april' => 4, 'may' => 5, 'june' => 6, 'july' => 7, 'august' => 8, 'september' => 9, 'october' => 10, 'november' => 11, 'december' => 12,
                'jan' => 1,'feb' => 2,'mar' => 3,'apr' => 4,'jun' => 5, 'jul' => 7,'aug' => 8, 'sep' => 9,'oct' => 10,'nov' => 11,'dec' => 12};
                
        Map<String, String> dayMap = new Map<String, String>
            {'Monday'=>'mon', 'Tuesday'=>'tue', 'Wednesday'=>'wed', 'Thursday'=>'thu', 'Friday'=>'fri', 'Saturday'=>'sat', 'Sunday'=>'sun'};
            
        Map <String, String > inputDatMap= new Map <String,String>();
             
     
                
                if(inputMask.equals('MMMM d, yyyy') || inputMask.equals('MMMMM dd, yyyy') || inputMask.equals('MMMMM dd, yy') || inputMask.equals('MMMMM d, yy') ||  
                    inputMask.equals('MMM d, yyyy')    || inputMask.equals('MMM dd, yyyy') || inputMask.equals('MMM dd, yy') || inputMask.equals('MMM d, yy') || 
                    inputMask.equals('MM d, yyyy') || inputMask.equals('MM dd, yyyy') || inputMask.equals('MM dd, yy') || inputMask.equals('MM d, yy'))                  {
                    String[] dateParts = srcDateTime.toLowerCase().replace(',','').split(' ');
                    Integer month = monthMap.get(dateParts[0]);
                    Integer dateVal = Integer.valueOf(dateParts[1]);
                    Integer year = Integer.valueOf(dateParts[2]);
                    parsedDate = Date.newInstance(year,month,dateVal);
                }else if(inputMask.equals(' MM/dd/yyyy'){
                    List <String> dateParts = srcDateTime.toLowerCase().replace('/','').split(' ');
                    Integer month = monthMap.get(dateParts[0]);
                    Integer dateVal = Integer.valueOf(dateParts[1]);
                    Integer year = Integer.valueOf(dateParts[2]);
                    parsedDate = Date.newInstance(year,month,dateVal);
                }else{
                    List <String> dateParts = srcDateTime.toLowerCase().replace(':','').split(' ');
                    Integer month = monthMap.get(dateParts[0]);
                    Integer dateVal = Integer.valueOf(dateParts[1]);
                    Integer year = Integer.valueOf(dateParts[2]);
                    parsedDate = Date.newInstance(year,month,dateVal);
                }
            }catch(Exception e){
                
            }
            
      
        return String.valueOf(parsedDate);
    }
Aniruddha ManakeshwarAniruddha Manakeshwar
The main problem I found here is I do not know what the positions will be for Date , Month , Year , Time (hour, minutes, second, milli seconds) , Once I get this positions, I will be in position to change it to the desired output format. Just a thought, appreciate if anyone has any suggestions. Looking forward for your reply.