Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

.net - Serializing DateTime to time without milliseconds and gmt

I have created a C# class file by using a XSD-file as an input. One of my properties look like this:

 private System.DateTime timeField;

 [System.Xml.Serialization.XmlElementAttribute(DataType="time")]
 public System.DateTime Time {
     get {
         return this.timeField;
     }
     set {
         this.timeField = value;
     }
 }

When serialized, the contents of the file now looks like this:

<Time>14:04:02.1661975+02:00</Time>

Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this?

<Time>14:04:02</Time>

Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized?

It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method.

The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put [XmlIgnore] on the Time property.

Then add a new property:

[XmlElement(DataType="string",ElementName="Time")]
public String TimeString
{
    get { return this.timeField.ToString("yyyy-MM-dd"); }
    set { this.timeField = DateTime.ParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture); }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...