Pierre Greborio.NET

Talking about .NET world

gYearMonth - DateTime mapping

gYearMonth represent a date (in a Gregorian calendar) formatted as yyyy-MM (.NET formatting string). In the current (Visual Studio .NET 2003 and 2005 beta) implementations, the gYearMonth type is mapped to System.String.

If you need to map it to a System.DateTime type you have to convert the System.String to System.DateTime throught ParseExact method, or implement your own type as following (please consider that the code isn't fully tested):

[XmlSchemaProvider("gYearMonthSchema")]
public class gYearMonth : IXmlSerializable
{
 private DateTime _value;

 public gYearMonth()
 {
  _value = DateTime.MinValue;
 }

 public gYearMonth(DateTime date)
 {
  _value = date;
 }

 public static implicit operator gYearMonth(DateTime date)
 {
  return new gYearMonth(date);
 }

 public static implicit operator DateTime(gYearMonth date)
 {
  return date._value;
 }

 public static XmlQualifiedName gYearMonthSchema(XmlSchemaSet set)
 {
  XmlQualifiedName n = new XmlQualifiedName("gYearMonth", "
http://www.w3.org/2001/XMLSchema");
  return (n);
 }

 public XmlSchema GetSchema()
 {
  throw new NotImplementedException();
 }

 public void ReadXml(System.Xml.XmlReader reader)
 {
  _value = DateTime.ParseExact(reader.ReadString(), "yyyy-MM", null);
 }

 public void WriteXml(System.Xml.XmlWriter writer)
 {
  writer.WriteString(_value.ToString("yyyy-MM"));
 }
}

The concept is generalizable to all date types.

Posted: Nov 28 2004, 09:48 AM by PierreG | with 1 comment(s)
Filed under:

Comments

TrackBack said:

# November 27, 2004 10:05 PM