簡體   English   中英

發布日期Web API自定義格式

[英]Post dates web api custom format

這是一場噩夢(至少我找不到簡單的方法),我已經搜索了數小時,但確實找不到解決方案。

如何在Web API中以自定義格式處理日期? 我需要DD / MM / YYYY格式

我無法發布日期,因為我的api希望它們采用默認格式MM / DD / YY,因此一種解決方案是通過JavaScript將我的所有日​​期解析為api需要的格式,但是是真的嗎? 這不是更干凈的方法嗎?

如何使我的api知道我的格式?

我發現了帖子,並說它不適用於發布。 尚無解決方案。

我做錯了嗎? 該問題的贊成票太多,甚至不是一個好的答案!

默認情況下,作為JSON格式化程序,在Web.Api中使用Json.NET序列化程序。 Json.NET以ISO 8601格式寫入日期。 UTC中的日期帶有“ Z”后綴。 當地時間中的日期包括時區偏移量。 例如:

2012-07-27T18:51:45.53403Z         // UTC
2012-07-27T11:51:45.53403-07:00    // Local

您可以通過在Web api配置部分中設置DateFormatString屬性來覆蓋Serrializer日期時間設置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd";
    }
}

另外,可能您需要在Global.asax中更改線程區域性設置

protected void Application_BeginRequest(object sender, EventArgs e)
{            
    var newCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
    newCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
    newCulture.DateTimeFormat.ShortTimePattern = "HH:mm";
    newCulture.DateTimeFormat.LongTimePattern = "HH:mm:ss";
    newCulture.DateTimeFormat.DateSeparator = "-";
    Thread.CurrentThread.CurrentCulture = newCulture;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM