How to select the format of $date in vm file?

36,300

Solution 1

Velocity provides a DateTool class for formatting dates. You would need to put an instance of this class into your velocity context:

context.add("date", new DateTool());

Then you could use a formatting command like:

$date.format('EEE, MMM d, yyyy at ha', $myDate)

to get something like Tuesday, February 26, 2013 at 11AM

Solution 2

Alternative solution that doesn't require additional dependency or code modification:

#set( $String = '' )##
$String.format('%1$tY%1$tm%1$td%1$tH%1$tM%1$tS', $date)

Combined from two other answers.

Solution 3

From the documentation:

Symbol   Meaning                 Presentation        Example
   ------   -------                 ------------        -------
   G        era designator          (Text)              AD
   y        year                    (Number)            1996
   M        month in year           (Text & Number)     July & 07
   d        day in month            (Number)            10
   h        hour in am/pm (1~12)    (Number)            12
   H        hour in day (0~23)      (Number)            0
   m        minute in hour          (Number)            30
   s        second in minute        (Number)            55
   S        millisecond             (Number)            978
   E        day in week             (Text)              Tuesday
   D        day in year             (Number)            189
   F        day of week in month    (Number)            2 (2nd Wed in July)
   w        week in year            (Number)            27
   W        week in month           (Number)            2
   a        am/pm marker            (Text)              PM
   k        hour in day (1~24)      (Number)            24
   K        hour in am/pm (0~11)    (Number)            0
   z        time zone               (Text)              Pacific Standard Time
   '        escape for text         (Delimiter)
   ''       single quote            (Literal)           '

   Examples: "E, MMMM d" will result in "Tue, July 24"
             "EEE, M-d (H:m)" will result in "Tuesday, 7-24 (14:12)"

Hope that helps

Solution 4

One of the backing Java classes must be putting it into the Context. If you want to format the date differently, you can do it in that class.

Another option would be to put the raw Date object into the context, then call methods in the Velocity template to format it. If need be you can pass Apache Commons DateUtils or another helper class to the template as well (see this answer).

Share:
36,300
aF.
Author by

aF.

Last time I checked,                 I was me.

Updated on July 26, 2022

Comments

  • aF.
    aF. almost 2 years

    I have a $date defined as "day of week, month day, year" ex: Tuesday, February 26, 2013

    I don't know where $date is defined but I like to add the hour to this $date variable, or create a variable with the hour, do you know how can I put it in the .vm file?