function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
parkerAPTparkerAPT 

Formatting Datetime Objects in VisualForce - how to?

Is there an easy way to only display the Time of a DateTime object in VisualForce?

 

Also is there an easy way to display the Day-of-the-week like 'Friday' in VisualForce?

 

Currently, I'm using a switch statement taken from the pdf on Formulas, but am wondering if there is a better method:

{!CASE(MOD( TODAY() - DATE(1900, 1, 7), 7),0, "Sunday",1, "Monday",2, "Tuesday",3, "Wednesday",4, "Thursday",5, "Friday",6, "Saturday", "Error")}

 

Thanks

Parker

 

Best Answer chosen by Admin (Salesforce Developers) 
JeremyKraybillJeremyKraybill

Phenomenal! Doug is saying that outputText, although not documented as such in the guide, exposes all the capabilities of MessageFormat from Java, see here. That, combined with the Java SimpleDateFormat syntax, see here, gives you what you need to be able to do this:

 

 

<apex:outputText value="string: {0,date,yyyy.MM.dd G 'at' HH:mm:ss z}"> <apex:param value="{!acct.CreatedDate}" /> </apex:outputText>

But this goes WAY beyond date formatting, message format is a very full-featured formatting tool, which supports choice formatting for plurals, etc. See all the examples in the above docs. Very exciting that this is a direct pass-through! Thanks for the tip Doug!

 

Jeremy Kraybill

Austin, TX

 

All Answers

michaelforcemichaelforce

There is a "format()" method in Apex for Date and DateTime variables.  I don't believe you can use it in visualforce page directly... but you could create a variable and have your controller do the formatting.

 

so, your VF page would say: {!myFormattedDate}

 

and your controller would say:

 

 

public String getMyFormattedDate(){ return myDate.format(); }

 

 If I am correct here... that should return the date in the locale of the running user.

 

parkerAPTparkerAPT

Michael,

 

If I was only formatting a single day, I could do what you suggested.  However, I'm formatting list of Events with start and ending times.  Although I could return an array of formatted Strings, its less than desireable and in my opinion, breaks the MVC paradigm.

 

If I get around to it, I'll suggest adding more powerful formatting to Idea exchange if there is not a similar idea already.

 

 

JeremyKraybillJeremyKraybill

The method you have described is really probably the most elegant way to do it currently. The format() method uses Java's much more expressive formatting strings, so is more powerful, but you are correct in that you can't directly access it from the VF template.

 

One semi-hack I use to store formatted dates for rendering against large lists of SObjects is to iterate over the list in the controller, and format() the date and then store into an unused string field of that SObject. Then you render that string field in your output. Not perfect but probably more elegant than trying to render parallel lists of strings. Another possibility is to create a wrapper class that exposes formatted SObject fields the way you want it, but that seems overkill here.

 

Jeremy Kraybill

Austin, TX

michaelforcemichaelforce

Reading about the "hack" (which totally sounds like something I would do) gave me another idea... you could create a formula field called "day_of_week__c" or whatever special format you need... and then your VF / controller would just need to query and display it.  In the end it may actually be more work then the way you described you are already doing it... but it's another way... in case it helps.

dchasmandchasman
apex:outputText already supports the the same String.format() functionality (actually does a pass through to that on the back end) - you just need to leverage child apex:param's inside the body of an apex:outputText and you should be able to accomplish what you want just using straight VF markup.
parkerAPTparkerAPT

Doug,

 

Can you provide a more concrete example of what child parameters to use?

I cannot find any reference in documentation on String and outputtext that would suggest outputtext supports this type of formatting:

String Documentation

 

 OutputText Documentation

 

I've tried the following with little success:

 

<apex:outputText value="{0}"> <apex:param value="{!item.ActivityDate}"/> </apex:outputText> <apex:outputText value="{0}"> <apex:param value="{!item.ActivityDate}"/> <apex:param value="HH:mm:ss"/> </apex:outputText>

 <apex:outputText value="{HH:mm:ss}">
<apex:param value="{!item.ActivityDate}"/>
</apex:outputText>

 

 Also, I accidently accepted the solution by clicking on the badge in your post, whoops cannot unAccept.

 

 

Thanks and I appreciate your help.

 

JeremyKraybillJeremyKraybill

Phenomenal! Doug is saying that outputText, although not documented as such in the guide, exposes all the capabilities of MessageFormat from Java, see here. That, combined with the Java SimpleDateFormat syntax, see here, gives you what you need to be able to do this:

 

 

<apex:outputText value="string: {0,date,yyyy.MM.dd G 'at' HH:mm:ss z}"> <apex:param value="{!acct.CreatedDate}" /> </apex:outputText>

But this goes WAY beyond date formatting, message format is a very full-featured formatting tool, which supports choice formatting for plurals, etc. See all the examples in the above docs. Very exciting that this is a direct pass-through! Thanks for the tip Doug!

 

Jeremy Kraybill

Austin, TX

 

This was selected as the best answer
parkerAPTparkerAPT

Phenomenal indeed!!

 

Thanks for all your help Doug and Jeremy. 

dchasmandchasman
FYI - I have opened a bug for the VF tech writer to get this added to the docs.
michaelforcemichaelforce
That's pretty tasty... you savvy java developers always have a leg up, eh? :smileyhappy:
Kirk F.ax361Kirk F.ax361

Doug and Jeremy, thanks for pointing out this feature.

 

In some cases, we need to render customer-facing text in a locale different from that of the current user.

 

The Constructor Summary for MessageFormat Jeremy refers to suggests that when passed two strings instead of one, it will treat the second as a locale (like "en-US" or "fr-FR" ) to guide formatting.  Is it possible to use this in outputText as well, using the MessageFormat syntax? 

For example, I confirm this works very well:

<apex:outputText value="Expiration Date: {0,date,long}">
<apex:param value="{!Opportunity.CreatedDate}" />
</apex:outputText>

 

But I can't seem to pass a locale in without causing "An internal server error has occurred Error ID: 44212127-14070 (1030573434)" when I try this:

<apex:outputText value="Expiration Date: {0,date,long,US}">
<apex:param value="{!Opportunity.CreatedDate}" />
</apex:outputText>

 

This errors out as well:

<apex:outputText value="Expiration Date: {0,date,long,Locale.US}">
<apex:param value="{!Opportunity.CreatedDate}" />
</apex:outputText>

 

I'm very happy with this powerful text formatting tool right in visualforce! Thanks for exposing it.  But I wonder if a syntax error on my part is keeping the locale formatting from working, or if passing in the locale is simply not available.

 

This will help, for example, a German-speaking colleague create a PDF document for a French customer, without the date appearing on the document in the wrong language and formatting style.

 

Thanks (make that Danke and Merci, as well).

 

 

 

 

 

 

 

 

 

kevin hekevin he

Since we can use the Datetime format in outputText, Does it exist a format to custom my currecny? 'cause you know, when the multi-currency is opened, I can not get the proper format using the outputField. Problem as follow:

 

<apex:outputField value="{!Account_Plan__c.Amount__c}"/>

 

I want to get the format like "$2,000.00", so I try this one:

 

<apex:outputText value="{0,Decimal,##,##,###}">

    <apex:param value="{!Account_Plan__c.Amount__c}"/>

</apex:outputText>

It doesn't work. I am not good at java and I am also not sure how to use it as the DateFormat.

 

Thank you very much!

Kirk F.ax361Kirk F.ax361

Kevin, try these links:

 

http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=2620
Formatting Currency fields in a multi-currency org

 

http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=894
Convert a double field into a currency field in Visualforce

 

The question on this thread, at least at this point, is how we can pass the locale into the format() command.

 

 

Message Edited by Kirk F on 03-04-2009 10:48 AM
Message Edited by Kirk F on 03-04-2009 10:51 AM
Philip_FPhilip_F

This solution is crashing when I attempt to use it inside a dataTable bound to a list.

 

This works fine:

 

<apex:dataTable value="{!someList}" var="List" id="theTable" cellpadding="4" border="2">        	
<apex:column>
<apex:facet name="header">Some Header</apex:facet>
<apex:outputText value="The Date: {0,date,yyyy.MM.dd G 'at' HH:mm:ss z}">
<apex:param value="{!NOW()}" />
</apex:outputText>
</apex:column>
</apex:dataTable>

 

But this causes SFDC to throw up:

 

<apex:dataTable value="{!someList}" var="List" id="theTable" cellpadding="4" border="2">        
<apex:column>
<apex:facet name="header">Some Header</apex:facet>
<apex:outputText value="The Date: {0,date,yyyy.MM.dd G 'at' HH:mm:ss z}">
<apex:param value="{!myCustomObject__c.MyDate__C}" />
</apex:outputText>
</apex:column>
</apex:dataTable>

 

The error message I'm getting is: 

 

An internal server error has occurred

 

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact support@salesforce.com. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience.

 

Thank you again for your patience and assistance. And thanks for using Salesforce!

 

Error ID: 624184484-7197 (1403973106)

 

It seems that SFDC can't support date formatting in a list like this.  Is there a good way to solve this?

 

Many thanks for all input!

 

Cheers,

-Philip 

 

 

 

 

Kirk F.ax361Kirk F.ax361

Philip, you may be trying to format a date variable, instead of a datetime.  To confirm, try this:

<apex:dataTable value="{!someList}" var="List" id="theTable" cellpadding="4" border="2">
<apex:column>
<apex:facet name="header">Some Header</apex:facet>
<apex:outputText value="The Date: {0,date,yyyy.MM.dd G 'at' HH:mm:ss z}">
<apex:param value="{!myCustomObject__c.CreatedDate}" />
</apex:outputText>
</apex:column>
</apex:dataTable>

 

Where "CreatedDate" is the native salesforce datetime variable on every object.  If that works, then you know the formatting parameters work well with DateTime variables, but not Date variables.  To solve, you can either cast your Date variable into a DateTime, or better yet define myDate__c as a DateTime.

 

Please share your results.

Message Edited by Kirk F on 03-23-2009 08:37 AM
Philip_FPhilip_F

Hello Kirk,

 

Thanks for tip to confirm that the formatting issue is with a datetime and not a date variable.   I ran the test as you recommended and still got the same error message from SFDC.

 

Interestingly, I found that if I don't use any formatting, the list values will display the date correctly, but that's of limited use.

 

This does not error:


<apex:dataTable value="{!someList}" var="List" id="theTable" cellpadding="4" border="2">        
<apex:column>
<apex:facet name="header">Some Header</apex:facet>
<apex:outputText value="The Date: {0}">
<apex:param value="{!myCustomObject__c.MyDate__C}" />
</apex:outputText>
</apex:column>
</apex:dataTable>

Kirk F.ax361Kirk F.ax361

OK -- then we may have a case to report.

If you can confirm that the formatted outputText fails when placed inside DataTable, but works well when on its own, maybe set that up as a page in your sandbox, and then log a case with salesforce against it.  I've done this before: they'll log in as you (if you grant that access), and confirm the problem.

 

Good find!  I'm sure we're not the only ones excited about this formatting feature,  and want to see it a useful stable feature.

SetupForceSetupForce

Hi

 

I'm getting the "An internal server error has occurred" error when attempting to format output text using list bound to a pageBlockTable.

 

Again, as in the dataTable example, it didn't crash when simply passing a value without any patterns.

 

I'm wondering if this error has been logged by anyone?

 

Regards

Paul

 

housingworkshousingworks

This is a good solution but it still formats the time as UTC, instead of correctly displaying it in the local time.  Why is it so hard to get the local time to display for my users on a visual force page

 

Please help!!! 

KnewTVsKnewTVs

This is what worked for me and is real simple....

 

 

<apex:column > <apex:facet name="header" ><b>Pickup Time</b></apex:facet> <apex:outputField value="{!a.PickupDateTime__c}" /> </apex:column>

JDevJDev

The problem is that a datetime outputfield is not useful for displaying lists of times in local timezone without displaying the date portion. The format expressions default to GMT and there's no documentation or examples of how to display just the time portion without the date in a specific locale - or even the default locale of the user. GMT is great for automated timing and time comparisons but with daylight savings time in many locales it is NOT good for user oriented time output, and including the date with every time is far too verbose.

 

If this is doable in visualforce an example would be most welcome, and if not it should be addressed soon..

hitesh Patelhitesh Patel

 

here is the code to format datetime in the such format i.e. [MM:dd:yyyy HH:MM AM/PM]
<apex:outputText value="{0,date,MM/dd/yyyy HH:MM a}">
           <apex:param value="{!dhw.createddate}"/>
</apex:outputText>

 

 

clarkbkclarkbk

Can anyone here explain why using the outputText param tags to expose the Java MessageFormats capability will not work inside a pageBlockTable or dataTable?  I've basically copy/pasted the working code from previous entries, but the visualforce editor fails to compile before rendering.

 

<apex:pageBlockTable value="{!closedOpportunities}" var="opps"> 

 

 <apex:column >
 <apex:facet name="header">Close Date</apex:facet>
 <apex:outputText value="{0,date,MM/dd/yyyy}">
 <apex:param value="{!opps.CloseDate}"/>
 </apex:outputText>
 </apex:column>
</apex:pageBlockTable>

The error message that the editor spits out is:

Error: The value attribute on <apex:outputText> is not in a valid format. It must be a positive number, and of type Number, Date, Time, or Choice.

FWIW, 'closedOpportunities' is a List<Opportunity> pulled from a SOQL query.

Help!  What am I missing?
JoyDJoyD

Was the local timezone issue ever resolved?  I was so thankful to have found this thread; I actually wrote a whole class to format the date the way I wanted, but found it ridiculous and couldn't believe visualforce didn't have such a feature.  Now it turns out it does...sooo close, yet so far away!  If I can't get it into the local timezone of the user, then it is useless :-(  Back to generic outputField instead...

KVaishnaKVaishna

Hi,

 

How can I convert time on Visualforce page from GMT to my local time zone?

 

Thanks,

-Kunjan

Jamie BrowningJamie Browning

Not a very well known solution to the local time issue of OutputText rendering GMT. Not sure if it is LTE supported, but it has worked as long as I know.

                                <apex:outputText value=" {!case.CreatedDate}"/>         

PUT A SPACE IN FRONT OF THE CURLY BRACKET ^

Will render Local TIme in local format instead of GMT.

Does not solve the answer above but this thread is often found for the Local TIme issue.