dateConvert Component

Someone recently was trying to resolve a problem of changing the timezone on a date field for use within a VisualForce email template. I threw together this quick component that can change the timezone as well as the format. There is a brief demo VisualForce page below I used on Account to view the created date. I’ll update the post later with some more detailed instructions on how to install this into your org for non developer types. And I will write some test code since you’ll need it to move this to production, but first I’m going to go celebrate my birthday.

dateConvert.component

<apex:component access="global" selfClosing="true" controller="dateConvert">
    <apex:attribute name="format" assignTo="{!dateFormat}" access="global" type="String" default="M/d/yyyy h:mm a" description="Format of the datetime field"/>
    <apex:attribute name="field" assignTo="{!dateField}" access="global" type="DateTime" required="true" description="Field to convert"/>
    <apex:attribute name="timezone" assignTo="{!dateTimezone}" access="global" type="String" default="GMT" description="Timezone to convert to"/>
    
    <apex:outputText value="{!output}"/>
</apex:component>

dateConvert.cls

public class dateConvert {
    public String dateTimeZone {
        get;
        set;
    }
    public DateTime dateField {
        get;
        set;
    }
    public String output {
        get {
            return dateField.format(this.dateFormat, this.dateTimeZone);
        }
    }
    public String dateFormat {
        get;
        set;
    }
}

Example usage in a VisualForce page

<apex:page standardController="Account">
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <c:dateConvert field="{!Account.CreatedDate}" timezone="America/Chicago"/><br/>
            </apex:pageBlockSectionItem>
            <apex:outputField value="{!Account.CreatedDate}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Leave a Reply

Your email address will not be published. Required fields are marked *