如何在 Freemarker 模板或 javascript 中以特定格式转换日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27857058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:47:20  来源:igfitidea点击:

How to convert date in specific format in Freemarker template or javascript

javascriptdatefreemarker

提问by rakesh

From json, i am getting the value as

从json,我得到的价值为

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

I am Accessing in FTL

我在 FTL 中访问

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

The result i am getting is

我得到的结果是

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

My preferable format is 09-01-2015

我的首选格式是 09-01-2015

I need to remove rest of the time GMT, IST and so on.

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

How to convert this in Freemarker template or javascript.

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

Update

更新

I tried to pass below like this

我试着像这样在下面通过

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

but it is giving error as

但它给出了错误

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

Any help is Appreciated.

任何帮助表示赞赏。

Thanks

谢谢

回答by ddekany

First of all, what format is that at all? I mean, if you can influence someone to use a standard format instead (ISO, mostly) that will help everyone. Anyway, FreeMarker isn't a date parser library, but actually you can do something like this:

首先,那到底是什么格式?我的意思是,如果您可以影响某人使用标准格式(主要是 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}

回答by Beri

Have you tried this?

你试过这个吗?

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

Here is link to documentation: http://freemarker.org/docs/ref_builtins_date.html

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

回答by Kristian Ivanov

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());

This should do the job. You can tweak it additionally

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

回答by arman1991

You can create your own custom function and use getDate, getMonthand getFullYearmethods to format your date.

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

Note that you must parse your string date format into Date object.

请注意,您必须将字符串日期格式解析为 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>

回答by Yan Khonski

I went this way. I created an object - formatter and pass it into template model. And I call formatter.format(date) in the template.

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

template.ftl

模板.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;
    }
}