web-dev-qa-db-ja.com

FreemarkerテンプレートまたはJavaScriptで特定の形式の日付を変換する方法

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

どんな助けも感謝しています。

ありがとう

7
rakesh

まず第一に、それはどのような形式ですか?つまり、誰かに代わりに標準フォーマット(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}
16
ddekany

これを試しましたか?

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

ここにドキュメントへのリンクがあります: http://freemarker.org/docs/ref_builtins_date.html

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

これでうまくいくはずです。あなたはそれをさらに微調整することができます

2
Kristian Ivanov

独自のカスタム関数を作成し、getDategetMonth、およびgetFullYearメソッドを使用して日付をフォーマットできます。

文字列の日付形式を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>
1
arman1991

私はこのように行きました。オブジェクトフォーマッターを作成し、テンプレートモデルに渡しました。そして、テンプレートで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;
    }
}
0
Yan Khonski