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}"/>

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: and sorry if I am stupid but not so obvious how to do this?

Many thanks.



For the following format

February 2, 2013

please use:

Datetime myDatetime =;
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(;
    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

Source : Link , Question Author : dublintech , Answer Author : Sergej Utko

Leave a Comment