mark_spencer mark_spencer - 1 year ago 101
C# Question

Convert string to correct date string

I have code that generates xml from database data.

Here is it

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


Data is takes from mobile app request. Mobile app sending c.StartDay for example like this
17-8-2017T10:8:3
. In xml I need to show it like this
yyyy-MM-ddTHH:mm:ss


How I can do this on xml generation?

Answer Source

You should first parse the string you are getting to a DateTime:

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

and then in the xml show it the way you like:

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

You can do all of that in one statement during your select:

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

Since linq-to-entities doesn't support these kind of method, you can use it after in the XmlElement:

new XElement("start", DateTime.ParseExact(w.StartDay,"d-M-yyyyTH:m:s", 
                                         CultureInfo.InvariantCulture)
                              .ToString("yyyy-MM-ddTHH:mm:ss")),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download