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

2019-04-20 16:00发布

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?

标签: java velocity
4条回答
The star\"
2楼-- · 2019-04-20 16:04

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.

查看更多
倾城 Initia
3楼-- · 2019-04-20 16:07

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

查看更多
地球回转人心会变
4楼-- · 2019-04-20 16:23

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).

查看更多
仙女界的扛把子
5楼-- · 2019-04-20 16:28

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

查看更多
登录 后发表回答