Convert DateTime to Date

  • I want to Convert DateTime into Date

    I have been trying this out ..below is the code snippet

    public void searchSFDC() {
        DateTime lastModDate ;
        for(sObject resultSet : searchResults[0]) { // searching only solutions
            SfResults sf = new SfResults();
            lastModDate=Datetime.valueOf(resultSet.get('LastModifiedDate'));
            sf.lastModifiedDate = date.newinstance(lastModDate.year(),lastModDate.month(),lastModDate.day());
         }
    }
    public class SfResults {
            public Date lastModifiedDate {get;set;}     
    }
    

    But sf.lastModifiedDate is shown as 2014-04-11 00:00:00 .I do not want the 00:00:00 timestamp .How can we achieve this?

    Where is it shown, on the page?

  • Datetime objects have this date method:

    date()

    Returns the Date component of a Datetime in the local time zone of the context user.

    so your code can use it like this:

    Datetime dt = (Datetime) resultSet.get('LastModifiedDate');
    sf.lastModifiedDate = dt.date();
    

    (Generally you would need a null check in the code but as LastModifiedDate always has a value here you don't.)

    So this gets you the correct Date object value. But an answer is needed to mast0r's question to cover how to get the final presentation right.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used