Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.
<apex:outputText value="{0, date, D}"><apex:param value="{!Date()}" /></apex:outputText>

This gets me the day # of the month but I need the postfix portion of the date ie: 2nd, 3rd, 4th.

share|improve this question

1 Answer 1

up vote 7 down vote accepted

You can utilize a method like this in your controller to append the suffix to the day portion of the date, but this approach won't work directly in VF using an <apex:param /> input into a formatter. You'll have to construct the date string in the controller.

Caveat: this code doesn't work as written for integer values greater than 100 - but there are few months with more than 100 days, so I figured it was safe enough as written.

public static String getDayOfMonthSuffix(Integer n) {
    if (n == null) {
        return '';
    }

    if (n >= 11 && n <= 13) {
        return 'th';
    }

    Integer modResult = Math.mod(n, 10);        
    if (modResult == 1) { 
        return 'st'; 
    } else if (modResult == 2) { 
        return 'nd'; 
    } else if (modResult == 3) { 
        return 'rd'; 
    } else { 
        return 'th';
    }
}

Update

Here's some example controller code and VF markup

VF

<apex:outputText value="{!showFormattedDate}" />

Apex

public with sharing YourController {

    public string showFormattedDate() {

        // get a date
        Date today = Date.today();

        // use some parameter substitution to build the string
        string formattedDate = String.format('{0} {1}, {2}', new List<String>{ today.month(), getDayOfMonthSuffix(today.day()), today.year() });

        return formattedDate;
    }

    public String getDayOfMonthSuffix(Integer n) {
        if (n == null) {
            return '';
        }

        if (n >= 11 && n <= 13) {
            return 'th';
        }

        Integer modResult = Math.mod(n, 10);        
        if (modResult == 1) { 
            return 'st'; 
        } else if (modResult == 2) { 
            return 'nd'; 
        } else if (modResult == 3) { 
            return 'rd'; 
        } else { 
            return 'th';
        }
    }
}
share|improve this answer
    
Hmm seems good, how do I get the result? <script ....> getDayOfMonthSuffix(????); </script> –  GeneralChad Jun 27 at 20:32
    
@GeneralChad Take a peek at the answer, I added a working example that should get you started. –  Mark Pond Jun 27 at 21:25
    
Thanks Mark! -- Now to get a date formatted into Quarters. ;) I think using FLOOR((MONTH(CloseDate)-1)/3) + 1 and a modified script from what you posted above might work. –  GeneralChad Jul 2 at 21:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.