[SalesForce] How to convert string into datetime format

Hello Everyone I'm new in sales force and I want to change datetime format so that first of all I got datetime and after that I have convert it to string with different format . Now I want to again convert this into datetime format but this give error invalid date time . my code is here …..

DateTime startDT2 = DateTime.newInstance(selectedDate.addDays(1), initialEndTime);
system.debug('select dt2>>>'+ startDT2); **output**=2014-12-09 8:00:00

String myDate = startDT2.format('M/d/yyyy h:mm a'); 
system.debug('select mydate>>>'+ myDate); **output**=12/9/2014 1:00 AM
Datetime dt = Datetime.valueOf(myDate);
system.debug('date_string >>>'+ dt);             **output**=invalid date/time 

So please anyone tell me about this or solve my problem .I'm really thank full for whom.

Best Answer

Please use parse() method instead of valueOf() method.

Datetime dt = Datetime.parse(myDate);

Please refer for more details on DateTime Methods: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_datetime.htm#apex_System_Datetime_parse

UPDATE:

I've provided the code for you which I tested.

DateTime startDT2 = DateTime.now();
system.debug('select dt2>>>'+ startDT2);
String myDate = startDT2.format('M/d/yyyy h:mm a'); 
system.debug('select mydate>>>'+ myDate);
Datetime dt = Datetime.parse(myDate);
system.debug('date_string >>>'+ dt);

The result is 16:18:50:041 USER_DEBUG [7]|DEBUG|date_string >>>2014-12-09 10:48:00