2017-08-17 100 views
1

我有從數據庫數據生成xml的代碼。將字符串轉換爲正確的日期字符串

這裏是它

public HttpResponseMessage Index(DateTime today) 
    { 
     var timeTables = db.TimeTables 
      .Where(c=> c.Today == today) 
      .Select(c => new 
      { 
       c.INN, 
       c.StartDay, 
       c.StartPause, 
       c.EndPause, 
       c.EndDay 
      }).AsEnumerable(); 

     var xdoc = new XDocument(
      new XElement("data", 
       timeTables.Select(w => 
        new XElement("worker", 
         new XAttribute("id", w.INN), 
         new XElement("start", w.StartDay), 
         new XElement("pause", w.StartPause), 
         new XElement("continue", w.EndPause), 
         new XElement("end", w.EndDay) 
        ) 
       ) 
      ) 
     ); 

     return new HttpResponseMessage() { Content = new StringContent(xdoc.ToString(), Encoding.UTF8, "application/xml") }; 
    } 

數據是從移動應用請求花費。移動應用程序發送c.StartDay例如像這樣17-8-2017T10:8:3。在xml我需要顯示它這樣的yyyy-MM-ddTHH:mm:ss

我怎麼能這樣做的XML生成?

+0

但'c.StartDay'還可以' 17-12-2017T10:45:55'?=! –

+0

是的。你是對的@ MongZhu –

+0

它必須記錄在'yyyy-MM-ddTHH:mm:ss' @MongZhu –

回答

3

你應該首先分析你得到一個DateTime字符串:

DateTime.ParseExact(c.StartDay,"d-M-yyyyTH:m:s", 
         CultureInfo.InvariantCulture) 

,然後在XML顯示它您喜歡的方式:

.ToString("yyyy-MM-ddTHH:mm:ss") 

你可以做所有的在您選擇的一個聲明中:

var timeTables = db.TimeTables 
     .Where(c=> c.Today == today) 
     .Select(c => new 
     { 
      c.INN, 
      StartDay = DateTime.ParseExact(c.StartDay,"d-M-yyyyTH:m:s", 
              CultureInfo.InvariantCulture) 
           .ToString("yyyy-MM-ddTHH:mm:ss"), 
      c.StartPause, 
      c.EndPause, 
      c.EndDay 
     }).AsEnumerable(); 

UPDATE

由於LINQ到實體不支持這些類的方法,你可以在以後的XmlElement使用它:

new XElement("start", DateTime.ParseExact(w.StartDay,"d-M-yyyyTH:m:s", 
             CultureInfo.InvariantCulture) 
           .ToString("yyyy-MM-ddTHH:mm:ss")), 
+1

你只需要在你的日期字符串中使用單個's'就可以計算單個數字秒。 – Chris

+0

謝謝@Chris,編輯 –

+0

讓這個'LINQ to Entities不能識別'System.String ToString(System.String)'方法,並且這個方法不能被轉換成存儲表達式。' –

0

試試這個:

w.StartDay.ToString("yyyy-MM-ddTHH:mm:ss"); 

或試試這個:

DateTime _latestDepartTime = DateTime.ParseExact(w.StartDay.ToString(), "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture); 

下一個解決方案:

DateTimeOffset.ParseExact(w.StartDay.ToString(), "yyyy-MM-ddTHH:mm:ss", 
                 CultureInfo.InvariantCulture) 

希望它可以幫助

+0

不,這不是幫助 –

+0

現在@mark_spencer嘗試,我已經編輯我的解決方案 – praguan

+0

但我不能在這種結構中使用 'XDOC VAR =新的XDocument( 新的XElement(「數據」, timeTables.Select (「start」,w.StartDay), 新的XElement(「暫停」,w.StartPause)(w => 新的XElement(「worker」, 新的XAttribute(「id」,w.INN), ) , 新的XElement(「continue」,w.EndPause), 新的XElement(「end」,w.EndDay) )' –

0

可以嘗試

DateTime dt = DateTime.Parse("2017-12-17 10:45:55");