简体   繁体   中英

DateTime.Now without fractional seconds

How can I actually convert DateTime.Now to xsd:datetime format 2004-04-12T13:20:00-05:00 and finally assign it to a DateTime property (not string ) of xsd:datetime type in the schema XSD?

Property:

public System.DateTime Timestamp {
        get {
            return this.timestampField;
        }
        set {
            this.timestampField = value;
        }

Xsd:

<!-- Timestamp Type - Timezone portion is required and fractional seconds are prohibited -->
    <xsd:simpleType name="TimestampType">
        <xsd:annotation>
            <xsd:documentation>Base type for a date and time stamp</xsd:documentation>
        </xsd:annotation>
        <xsd:restriction base="xsd:dateTime">
            <xsd:pattern value="[1-9][0-9]{3}\-.+T[^\.]+(Z|[\+\-].+)"/>
        </xsd:restriction>
    </xsd:simpleType>

Tried Following:

Timestamp = Datetime.Now;
Timestamp = DateTime.ParseExact(DateTime.Now.ToString("O"), "O", CultureInfo.InvariantCulture);

I am getting following in the xml which is invalid as per the xsd schema validation

<Timestamp>2014-07-18T17:27:04.3185791-04:00</Timestamp>

I am trying to find out how to assign proper value to the Timestamp property which is valid according to the xsd pattern. ie.,2004-04-12T13:20:00-05:00 without fractional seconds.

If you look at this MSDN article you find that it states( emphasis mine ):

Internally, DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001 . The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.

Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its ToString method. The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default DateTime.ToString() method to display the date and time using the short date and long time pattern for the en-US culture, the current culture on the computer on which the example was run.

So based on that, you may want to try creating a new DateTime object from the specific fields of your TimeStamp that you created from DateTime.Now this will zero out the ticks that represent time intervals less than a second. If that doesn't work you probably are using the wrong Type, use a string instead.

ie

Timestamp = Datetime.Now;
Timestamp = new DateTime(Timestamp.Year,Timestamp.Month,Timestamp.Day,Timestamp.Hour,Timestamp.Minute,Timestamp.Second,Timestamp.Kind);

The type of the field or property that you actually write to the XML should probably be String or possibly a custom type, not a DateTime , which has some special handling anyway built into XmlSerializer . However, you can certainly have a DateTime property that abstracts getting and setting of the underlying field.

Here's an example:

using System;
using System.Xml.Serialization;

namespace Sandbox2
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            var now = DateTime.Now;
            var m = new Moment () { Timestamp = now };
            var xs = new XmlSerializer (typeof(Moment));
            xs.Serialize (Console.Out, m);
        }
    }

    public class Moment
    {
        [XmlElement("Timestamp")]
        public string BackingTimestamp;

        [XmlIgnore]
        public DateTime Timestamp
        {
            get
            {
                return DateTime.Parse (BackingTimestamp);
            }
            set
            {
                BackingTimestamp = value.ToString ("yyyy-MM-ddTHH:mm:ssK");
            }
        }
    }
}

Relevant part of the output:

<Timestamp>2014-07-19T12:20:24-05:00</Timestamp>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM