【问题标题】:How to convert date in specific format in Freemarker template or javascript如何在 Freemarker 模板或 javascript 中以特定格式转换日期
【发布时间】:2015-03-07 13:36:44
【问题描述】:

从 json 中,我得到的值是

"createdOn": "Jan 08 2015 20:40:56 GMT+0530 (IST)",

我在 FTL 中访问

<#list variables as variable>
  <div class="reply">
   ${variable.createdOn}
  </div>
</#list>

我得到的结果是

Jan 09 2015 12:36:18 GMT+0530 (IST)

我更喜欢的格式是 09-01-2015

我需要删除其余时间 GMT、IST 等。

如何在 Freemarker 模板或 javascript 中转换。

更新

我试着像这样通过下面

${variable.createdOn?datetime?string("dd-MM-yyyy")}

但它给出了错误

Exception: java.text.ParseException - Unparseable date: "Jan 09 2015 12:36:18 GMT+0530 (IST)"

感谢任何帮助。

谢谢

【问题讨论】:

    标签: javascript date freemarker


    【解决方案1】:

    你试过了吗?

    "${variable.createdOn?datetime?string('dd-MM-yyyy')}"
    

    这里是文档链接:http://freemarker.org/docs/ref_builtins_date.html

    【讨论】:

    • @Beri,我试过这个。它给了Exception: java.text.ParseException - Unparseable date: "Jan 09 2015 12:36:18 GMT+0530 (IST)"
    • @rakesh 我相信你应该用单引号替换双引号。
    【解决方案2】:

    您可以创建自己的自定义函数并使用getDategetMonthgetFullYear 方法来格式化您的日期。

    请注意,您必须将字符串日期格式解析为 Date 对象。

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click the button to display todays day of the month in dd-MM-yyyy format.</p>
    
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    function myFunction() {
        var d = new Date("Jan 08 2015 20:40:56 GMT+0530 (IST)"); //parsing your string date format into Date object.
    
    var z = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
       
        document.getElementById("demo").innerHTML = z;
    }
    </script>
    
    </body>
    </html>

    【讨论】:

    • 谢谢你,arman,但这并没有解决我的问题。创建日期可能会有所不同,例如昨天、今天或一个月前。我的意思是说我需要从 json 中读取它。对不起,如果我不清楚。
    • 我编辑了我的代码。您必须将字符串格式从 JSON 解析为 Date 对象
    • 您还想打印“昨天”、“前一个月”等选项 - 取决于您的日期?
    【解决方案3】:
    function convertDate( date ){
        dateSplit = date.toString().split( ' ' );
        dateSplit[1] = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : date.getMonth() + 1;
        return dateSplit[2] + '-' + dateSplit[1] +  '-' + dateSplit[3];
    }
    
    convertDate(new Date());
    

    这应该可以完成工作。你可以额外调整它

    【讨论】:

    • @Bowdzone,感谢您的编辑建议,这是我的第一次回复,我没有注意到它:)
    【解决方案4】:

    首先,那到底是什么格式?我的意思是,如果您可以影响某人改用标准格式(主要是 ISO),这将对每个人都有帮助。无论如何,FreeMarker 不是一个日期解析器库,但实际上你可以这样做:

    <#-- Settings you need -->
    <#setting date_format="dd-MM-yyyy">
    <#setting locale="en_US">
    
    <#-- The string that comes from somewhere: -->
    <#assign createdOn = 'Jan 08 2015 20:40:56 GMT+0530 (IST)'>
    
    <#--
      1. Tell FreeMarker to convert string to real date-time value
      2. Convert date-time value to date-only value
      3. Let FreeMarker format it according the date_format setting
    -->
    ${createdOn?datetime("MMM dd yyyy HH:mm:ss 'GMT'Z")?date}
    

    【讨论】:

    • 谢谢你..这是工作&lt;#setting date_format="dd-MM-yyyy"&gt; &lt;#setting locale="en_US"&gt; &lt;#assign createdOn = variable.createdOn&gt; ${createdOn?datetime("MMM dd yyyy HH:mm:ss 'GMT'Z")?date}
    【解决方案5】:

    我走这条路。我创建了一个对象格式化程序并将其传递给模板模型。我在模板中调用 formatter.format(date)。

    template.ftl

    <div class="historyOrderItem">
        <div>
        <div>Created <#if order.created??>${formatter.format(order.created)}</#if></div>
        <div>Amount ${order.amount!}</div>
        <div>Currency ${order.currency!}</div>
    </div>
    

    OrderPresenter.java

    @Component
    public class OrderPresenter {
    
        private static final String FORMATTER_PARAM = "formatter";
        private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        private static final DateTimeFormatter FORMATTER =
                DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).withZone(ZoneId.systemDefault());
    
        private Configuration configuration = prepareConfiguration();
    
        public String toHtmlPresentation(ClientDetails clientDetails) {
            try {
                Template template = configuration.getTemplate(CLIENT_DATA_TEMPLATE);
                Writer out = new StringWriter();
                template.process(toMap(clientDetails), out);
                return out.toString();
            } catch (IOException | TemplateException e) {
                throw new RuntimeException(e);
            }
        }
    
        private Configuration prepareConfiguration() {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
            configuration.setDefaultEncoding(ENCODING);
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            configuration.setLogTemplateExceptions(NOT_TO_LOG_EXCEPTIONS);
            configuration.setClassForTemplateLoading(OrderPresenter.class, TEMPLATES_FOLDER);
            return configuration;
        }
    
        private Map<String, Object> toMap(ClientDetails clientDetails) {
            Map<String, Object> res = new HashMap<>();
            res.put(CLIENT_DETAILS_PARAM, clientDetails);
            res.put(FORMATTER_PARAM, FORMATTER);
            return res;
        }
    }
    

    【讨论】:

      【解决方案6】:

      template.ftl

      <#list listaCategoria as c>
         <tr>
            <td> ${c.dataCadastro?datetime("yyyy-MM-dd")?string("dd/MM/yyyy")}</td>
         </tr>
      </#list>
      

      RelatorioService.java

      LocalDate dataCadastro = LocalDate.of(1995, 12, 7);
      

      结果:

      07/12/1995
      

      【讨论】:

        猜你喜欢
        • 2019-02-17
        • 2017-06-07
        • 2021-04-27
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 2021-12-09
        • 2014-11-17
        相关资源
        最近更新 更多