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

元气小坏坏 提交于 2019-12-22 03:42:32

问题


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?


回答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




回答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.




回答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




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



来源:https://stackoverflow.com/questions/15092372/how-to-select-the-format-of-date-in-vm-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!