2017-10-15 33 views
0

我將包含許多事物(包括DateTime)的一些JSON數據傳遞給我的視圖。我目前在控制器中將它編碼爲ISO格式,因此我將2017-10-13T23:21:00作爲我的日期,但我不確定如何將其更改爲更友好的10/13/17 11:21pm在MVC視圖中爲JQuery設置日期時間格式

目前它正在視圖中呈現爲JavaScript腳本的一部分。具體的部分是:

var template = "<tr><td>${DateTime}</td><td>${OtherStuff}</td></tr>" 

我試圖

var dt = new Date("${DateTime}") 
var template = "<tr><td>" + dt + "</td><td>${OtherStuff}</td></tr>" 

沒有成功(而不是我收到了「無效的日期」的預期輸出)。我收到的錯誤導致我認爲自己正朝着正確的道路前進,只是輕微地過關。


添加一些其他代碼的情況下,它可以幫助

這是

$(function() { 
    var data = @Html.Raw(Json.Encode(Model)); 
    var renderTable = function (success, error) { 
     var dt = new Date("${DateTime}"); 
     var template = "<tr><td>" + dt + "</td><td>${OtherStuff}</td></tr>" 

     if (success) { 
      $("#table tbody").empty(); 
       $($.ig.tmpl(template, ds.dataView())).appendTo("#table tbody"); 
      } else { 
       alert(error); 
      } 
     } 

     //This code creates an $.ig.DataSource from JSON data 
     var ds = new $.ig.DataSource({ 
      type: "json", 
      dataSource: data, 
      callback: renderTable 
     }); 

     // Binds to the underlying data 
     ds.dataBind(); 
    }); 

所有部分,我相信我現在看到的問題,模板僅僅是一個模板,這樣我就可以格式化稍後將被填充的佔位符變量。但我該怎麼做?

+1

庫,例如moment.js有利於處理日期和削減了很多手工編碼 – charlietfl

+0

嘗試jQuery的日期格式https://github.com/phstc/jquery-dateFormat我認爲「MM/dd/yyyy hh:mm」是am/pm格式 – derloopkat

+0

這兩者看起來都很整潔,但我並沒有在如何使用它們的上下文中使用它們。 – gilliduck

回答

0

您可以在您的日期對象上調用toLocaleString()方法以使其對語言友好。

var defaultDate = new Date("2017-10-13T23:21:00"); // Fri Oct 13 2017 23:21:00 GMT+0200 (Central Europe Daylight Time) 
var languageFriendlyDate = defaultDate.toLocaleString(); // 10/13/2017, 11:21:00 PM 

您還可以將特定區域設置作爲toLocaleString()方法的參數傳遞。

// US English uses month-day-year order and 12-hour time with AM/PM 
console.log(date.toLocaleString('en-US')); 
// → "12/19/2012, 7:00:00 PM" 

有關詳情,請: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

相關問題