简体   繁体   English

DateTime.Now没有小数秒

[英]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? 我如何实际将DateTime.Now转换为xsd:datetime格式2004-04-12T13:20:00-05:00并最终将其分配给架构XSD中的xsd:datetime类型的DateTime属性(不是string )?

Property: 属性:

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

Xsd: 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 我按照xsd架构验证在xml中跟随无效

<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. 我试图找出如何为Timestamp属性分配适当的值,该属性根据xsd模式有效。 ie.,2004-04-12T13:20:00-05:00 without fractional seconds. 即。,2004-04-12T13:20:00-05:00没有小数秒。

If you look at this MSDN article you find that it states( emphasis mine ): 如果您查看此MSDN文章,您会发现它( 强调我的 ):

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 . 在内部, DateTime值表示为自0001年1月1日午夜12:00:00起经过的刻度数(100纳秒间隔的数量) 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. 实际的DateTime值与在用户界面元素中显示或写入文件时该值的显示方式无关。 The appearance of a DateTime value is the result of a formatting operation. DateTime值的出现是格式化操作的结果。 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. 由于日期和时间值的出现取决于诸如文化,国际标准,应用程序要求和个人偏好等因素,因此DateTime结构通过其ToString方法的重载在格式化日期和时间值方面提供了极大的灵活性。 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. 默认的DateTime.ToString()方法使用当前区域性的短日期和长时间模式返回日期和时间值的字符串表示形式。 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. 以下示例使用默认的DateTime.ToString()方法,使用en-US文化的短日期和长时间模式显示日期和时间,en-US文化是运行该示例的计算机上的当前文化。

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. 因此,基于此,您可能希望尝试从DateTime.Now创建的TimeStamp的特定字段中创建新的DateTime对象。现在,这将使表示小于一秒的时间间隔的刻度为零。 If that doesn't work you probably are using the wrong Type, use a string instead. 如果这不起作用,您可能使用了错误的Type,请改用字符串。

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 . 实际写入XML的字段或属性的类型可能应该是String或可能是自定义类型,而不是DateTime ,它在XmlSerializer内置了一些特殊处理。 However, you can certainly have a DateTime property that abstracts getting and setting of the underlying field. 但是,您当然可以拥有一个DateTime属性来抽象获取和设置基础字段。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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