0
String dateTimeString = '1970-01-08T23:45:27.461Z';
dateTimeString = dateTimeString.substring(0, dateTimeString.indexOf('.'));

system.debug('dateTimeString'+dateTimeString);  results in 1970-01-08T23:45:27

dateTimeString = dateTimeString.replace('T', ' ');

system.debug('dateTimeString'+dateTimeString); results 1970-01-08 23:45:27

here the string representing date in format yyyy-mm-dd 23:45:27 but i want to format it to mm-dd-yyyy 23:45:27 ....

2 Answers 2

2

You dont have to do substring or replace on the date. You can use the Datetime.format() method to get the output in the expected format.

For Example:

Datetime myDT = Datetime.now(); // Returns the current Datetime based on a GMT calendar.
String myDate = myDT.format('mm-dd-yyyy HH:mm:ss'); // formats the date
system.debug('myDate='+myDate);
3
  • thanks.. but i was getting an error if my input datetime is 1970-01-08 23:45:27 by using your logic it is returning 45-08-1970 23:45:27 in place of 1st month it is displaying 45 i have changed mydt.format to mydt.formatGmt
    – Rajasekhar
    Apr 21, 2015 at 6:19
  • seems to be it's projecting minutes mm in place of months mm
    – Rajasekhar
    Apr 21, 2015 at 6:23
  • it's working i changed mm to MM
    – Rajasekhar
    Apr 21, 2015 at 6:26
1

Once you've normalised the date/time string, simply convert it to a DateTime variable and format it:

DateTime myDateTime = DateTime.valueOf(dateTimeString);
dateTimeString = myDateTime.formatGMT('MM-dd-yyyy HH:mm:ss');

You can read more around other ways to format the date/time and some other Force.com DateTime methods available.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .