I wrote soql and retrieved DateTime. ie) '2018-11-21T10:51:12.421Z'

I would like to split Date, hours:mins like '21-11-2018 10:51'. i tried like below,

String value = '2018-11-21T10:51:12.421Z';

String[] dateAndTime = value.split('T');
String[] dateParts = dateAndTime[0].split('-');

system.debug('dt---'+date.newinstance(Integer.valueOf(dateParts[0]), Integer.valueOf(dateParts[1]),Integer.valueOf(dateParts[2])));

O/P : 2018-11-21 00:00:00

Iam expecting '21-11-2018 10:51' . dont know why hh:mm showing 00:00


While there are certainly exceptions, it's usually best to rely on Apex to handle Date and Date-Time formatting. The DateTime.format() method will return a String that's converted to the local date time and locale format of the context user.

In this case, you have two separate issues.

  1. Your code extracts the Date value, which is dateAndTime[0], but does nothing with the Time value, which is dateAndTime[1]. Your code is creating a Date, which inherently has no time value associated with it.
  2. You are looking at a version of the Date as printed by System.debug(), which formats Date values as if they have a time value of midnight. That's where the 00:00:00 comes from.
  • HI @David Reed , thanks for your response. do you have any sample in apex to handle this situation? – Raja vel Jan 6 at 16:47
  • I can't write the code for you, Raja, and I don't really know what your objective is. I would recommend you read through the documentation on the format() method and see if that solves your problem. – David Reed Jan 6 at 16:49
  • Hi @David Reed, yes i read the developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… .. found solutions. Thanks. – Raja vel Jan 6 at 16:51
  • HI @David Reed, String val = '2018-11-21T10:51:12.421Z'; DateTime date1 = (DateTime)Json.deserialize('"'+val+'"', DateTime.class); System.debug('oooo'+date1.format()); working as expected.. – Raja vel Jan 6 at 16:56

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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