1
votes

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 gives an error, invalid date time. My code is:

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 

How to solve my problem?

2

2 Answers

1
votes

From the documentation of Datetime.valueOf():

The specified string should use the standard date format “yyyy-MM-dd HH:mm:ss” in the local time zone.

You can't use 12/9/2014 1:00 AM string and convert it to Datetime.

1
votes

If the users locale is English (United States) then you can use the DateTime.parse(string) method:

Constructs a Datetime from the String datetime in the local time zone and in the format of the user locale.

Example
This example uses parse to create a Datetime from a date passed in as a string and that is formatted for the English (United States) locale. You may need to change the format of the date string if you have a different locale.

Datetime dt = DateTime.parse('10/14/2011 11:46 AM');
String myDtString = dt.format();
system.assertEquals(myDtString, '10/14/2011 11:46 AM');

Incidentally, the Salesforce StackExchange site is a great place to ask Salesforce specific questions.