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.


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


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

  • I have already use this but I have same problem. basically I want to change my date time format i.e. suppose my date time 09-12-2014 11:00 PM convert into 09-12-2014 23:00 or vice verse . Dec 9 '14 at 10:46
  • Please check the Update section of my answer. I used the format given by you. It got me the result successfully. Please re-check your code once!
    – Vignex
    Dec 9 '14 at 10:52
  • I'm not getting the time part after datetime.parse. e.g. select mydate>>>12/9/2014 5:00 AM after parse is date_string >>>2014-12-09 00:00:00.
    – Mahmood
    Dec 9 '14 at 10:57
  • Please add your entire debug logs for your code above!
    – Vignex
    Dec 9 '14 at 11:14
  • 1
    +1 vignex: my bad. I was using date.today(). Updated it with datetime.now() and it works. offcourse, date.today() makes the time part 00:00:00 . :)
    – Mahmood
    Dec 9 '14 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.