I am trying to convert string from google docs "1/16/2019 11:52:38" to standard system date "2019-01-16 00:00:00". I was able to achieve that using substring method but I am pretty sure there is a faster and smarter way of doing this.

I would really appreciate your help!

My method

private Date getFormattedDate(String timestamp) {
    String dateAsString = timestamp.substringBefore(' ');
    Integer month = Integer.valueOf(dateAsString.substringBefore('/'));
    Integer year =  Integer.valueOf(dateAsString.substringAfterLast('/'));
    Integer day = Integer.valueOf(dateAsString.substringAfter('/').substringBeforeLast('/'));
    return Date.newInstance(year, month, day);

You can use Date.parse method:

String str = '1/16/2019 11:52:38';  
Date dt = Date.parse( str.split(' ')[0] );  
system.debug(' Parsed Date is ' + dt ); 

|DEBUG| Parsed Date is 2019-01-16 00:00:00

Refer Date Class

If you want to change from mm/dd/yyyy to dd/mm/yyyy format, use below approach.

Date dToday = Date.today(); //DEBUG|>>>>2019-01-17 00:00:00
String dateStr = Date.today().format();
DateTime dt = DateTime.newInstance(dToday.year(), dToday.month(),dToday.day());
dateStr = dt.format('dd/MM/yyyy');
System.debug('>>>>' + dateStr); //>>>>17/01/2019
  • This is what I have already tested, it throws an error "Invalid date: 1/15/2019" :( – Tomek Jan 17 at 10:10
  • It works fine for me and given result as 2019-01-15 00:00:00 – Reshma Jan 17 at 10:13
  • May be it won't support in your locale. What is your locale? – Reshma Jan 17 at 10:15
  • That seems to be right, is it possible to just change mm/dd/yyyy to dd/mm/yyyy in apex? – Tomek Jan 17 at 10:46
  • Yes @Tomek . First convert date to datetime and you can use Datetime.format('dd/MM/yyyy') – Reshma Jan 17 at 11:43

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.