Activity Forums Salesforce® Discussions How to convert string date format in Salesforce Apex?

  • Anurag

    Member
    August 23, 2018 at 3:04 pm

    Hi Shradha,

    Here is the way to do it:

    String TimeString = '4:33:34 PM';
    String Regex = '(\\d{1,2}):(\\d{1,2}):(\\d{1,2}) ([PA]M)';
    Pattern p = Pattern.compile( Regex );
    Matcher m = p.matcher( TimeString );

    if ( m.matches() ){
    Integer Hours = Integer.valueOf( m.group(1) )
    , Minutes = Integer.valueOf( m.group(2) )
    , Seconds = Integer.valueOf( m.group(3) )
    , PmShift = m.group(4) == 'PM' ? 12 : 0
    ;

    Time t = Time.newInstance( Hours + PmShift , Minutes , Seconds , 0 );

    System.debug( (''+t).substring(0,(''+t).indexOf('.')) );
    }

  • shariq

    Member
    September 19, 2018 at 12:43 am

    Hi,

    Try this -

    private Date setStringToDateFormat(String myDate) {
    String[] myDateOnly = myDate.split(' ');
    String[] strDate = myDateOnly[0].split('/');
    Integer myIntDate = integer.valueOf(strDate[1]);
    Integer myIntMonth = integer.valueOf(strDate[0]);
    Integer myIntYear = integer.valueOf(strDate[2]);
    Date d = Date.newInstance(myIntYear, myIntMonth, myIntDate);
    return d;
    }

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos