0

I am writing a program in c# that serializes objects to XML

I am having trouble with the date and time fields, they do not produce the following output in XML:

2014-05-13T00:00:00
0000000T18:35:00

I have declared the fields as following in my program:

public DateTime startDate
public DateTime startTime

Can anyone help so that the date is correctly outputted to XML file?

Thank you

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
xirokx
  • 37
  • 7

3 Answers3

1

You don't have to declare startTime to get the input you want. Just parse your datetime like this:

DateTime startDate = new DateTime(2014, 5, 13, 18, 35, 0);
startDate.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff");//2014-05-13T18:35:00.000000  

You can also check my answer regarding to formating datetime.

Community
  • 1
  • 1
Bura Chuhadar
  • 3,653
  • 1
  • 14
  • 17
  • I ended up using this and it works a treat: startDate = DateTime.TryParse("2014/5/13", out scheduleDate) ? scheduleDate.ToString("dd-MM-yyyy") : ""; thanks for your help – xirokx Jun 04 '14 at 14:41
1

DateTime represents both date and time, so really only one variable would be enough:

public DateTime startTimestamp;

You can then create the string representations you want from that single datetime value like this:

string dateValue = startTimestamp.Date.ToString("yyyy-MM-ddTHH:mm:ss");

Problem is that "00000000" is not a valid date, so you need to do your own formatting:

string timeValue = "00000000T" + startTimestamp.ToString("HH:mm:ss");

The question actually is why you want to store the (empty) time part and the (invalid) date part in your XML when you could just store either date and time within one value or date and time in separate values like this:

string dateTimeValue = startTimestamp.ToString("yyyy-MM-ddTHH:mm:ss");
string dateOnly = startTimestamp.ToString("yyyy-MM-dd");
string timeOnly = startTimestamp.ToString("HH:mm:ss");
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
0

If the field startTime is storing time with timezone then please note that the literal structure for xs:time datatype is

hh:mm:ss[Z|(+|-)hh:mm].

0000000T18:35:00 seems to be invalid.

thinkster
  • 586
  • 2
  • 5
  • 19
  • I ended up using this and it works a treat: startDate = DateTime.TryParse("2014/5/13", out scheduleDate) ? scheduleDate.ToString("dd-MM-yyyy") : ""; thanks for your help – xirokx Jun 04 '14 at 14:41
  • Cool. I believe then you wanted to ignore time and just save Date information. If you wanted to include time it would be `scheduleDate.ToString("R")` for including the timezone or `scheduleDate.ToString("F")` without that. – thinkster Jun 04 '14 at 15:21