Getting format for date

  • In a visual force page, I can take a date and do this...

    <apex:outputText value="{0,date, MMMM d,  yyyy}">
        <apex:param value="{!relatedTo.my_date__c}"/>
    </apex:outputText>
    

    I want to be able to do that in Apex code. So I want a method which takes a date and returns a certain format as a string.

    I check the API: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_date.htm and sorry if I am stupid but not so obvious how to do this?

    Many thanks.

  • Sergej Utko

    Sergej Utko Correct answer

    8 years ago

    UPDATE

    For the following format

    February 2, 2013

    please use:

    Datetime myDatetime = Datetime.now();
    String myDatetimeStr = myDatetime.format('MMMM d,  yyyy');
    

    Im using the following functions for the timestamp:

    // This method returns a whole timestamp as a string
    public String timeStamp(){
        Datetime dt = Datetime.NOW();
        String day = checkLength(String.valueOf(dt.day()));
        String month = checkLength(String.valueOf(dt.month()));
        String hour = checkLength(String.valueOf(dt.hour()));
        String minute = checkLength(String.valueOf(dt.minute()));
        String second = checkLength(String.valueOf(dt.second()));
    
        return = String.valueOf(dt.year()) + month + day + '-' + hour + minute + second;
    }
    
    // Here i check the length of the day/month/...
    // because the month() for example can return 3 for March and i want to have 03
    private String checkLength(String val){
        if(String.isNotBlank(val) && val.length() == 1){
            val = '0' + val;
        }
        return val;
    }
    

    And my output looks like this then: 2013.02.08 08:30:56

    Thanks suppose you wanted your output to look like February 2, 2013

    @dublintech just updated & simplified my example

    Your `timeStamp()` method seems very inefficient -- how could you refactor it to just use the `Datetime.format()` method and still get the same output? Post that and I'll remove my downvote.

    @mast0r I agree with @tomlogic. Your implementation for `timeStamp()` is very inefficient and is a bad example. It would be much more efficient to use the `DateTime.format()` e.g. `DateTime.now().format('yyyyMMdd - HHmmss')`

License under CC-BY-SA with attribution


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

Tags used