简体   繁体   中英

Convert DateTime to a specific format

What is the best and fastest way to convert a DateTime to this format?

2015-03-26T18:02:58.145798Z

Currently I receive a date from a server and I'm able to parse it and convert the date in to DateTime and the ToString() output is something like this:

26/03/2015 18:02:58

For converting the date I'm using this line of code:

var parsedDate = DateTime.Parse("2015-03-26T18:02:58.145798Z", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

What is the best way to convert parsedDate back to the original format?

EDIT: I want to convert the DateTime to this format 2015-03-26T18:02:58.145798Z as string

If you have a DateTime object you can convert it to a string with that particular format by using O as format specifier:

parsedDate.ToString("O")

or

parsedDate.ToUniversalTime().ToString("O") // if parsedDate is not UTC

returns "2015-03-26T18:02:58.1457980Z" .


If the DateTimeKind of your DateTime object is not Utc then you won't get the Z extension at the end of the string according to ISO8601. In the example you provided the Z is present because DateTime.Parse will recognize it and return a DateTime in Utc . Should the Z be missing in the original string you parse you can still assume it's UTC by using ToUniversalTime() on the date time object.

The answer is almost what @Dirk said:

parsedDate.ToString("O") is the line, but you have to convert the DateTime to UTC: that's how you get the "Z" at the end.

See https://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx for more info.

Edit:

To convert a DateTime to UTC, use the ToUniversalTime() method.

The FASTEST way, known to me, is this:

        ///<summary>Format the date time value as a parsable ISO format: "2008-01-11T16:07:12Z".</summary>
    public static string ISO( this DateTime dt ) {
        var ca = new char[] {
            (char) ( dt.Year / 1000 % 10 + '0' ),
            (char) ( dt.Year / 100 % 10 + '0' ),
            (char) ( dt.Year / 10 % 10 + '0' ),
            (char) ( dt.Year % 10 + '0' ),
            '-',
            (char) ( dt.Month / 10 + '0' ),
            (char) ( dt.Month % 10 + '0' ),
            '-',
            (char) ( dt.Day / 10 + '0' ),
            (char) ( dt.Day % 10 + '0' ),
            'T',
            (char) ( dt.Hour / 10 + '0' ),
            (char) ( dt.Hour % 10 + '0' ),
            ':',
            (char) ( dt.Minute / 10 + '0' ),
            (char) ( dt.Minute % 10 + '0' ),
            ':',
            (char) ( dt.Second / 10 + '0' ),
            (char) ( dt.Second % 10 + '0' ),
            'Z',
        };
        return new string( ca );
    }

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