我有从数据库数据生成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 :(得分: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();
<强>更新强>
由于linq-to-entities不支持这种方法,您可以在XmlElement
之后使用它:
new XElement("start", DateTime.ParseExact(w.StartDay,"d-M-yyyyTH:m:s",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-ddTHH:mm:ss")),
答案 1 :(得分: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)
希望有所帮助
答案 2 :(得分:0)
DateTime dt = DateTime.Parse("2017-12-17 10:45:55");