Given a DateTime object, how do I get an ISO 8601 date in string format?












671















Given:



DateTime.UtcNow


How do I get a string which represents the same value in an ISO 8601-compliant format?



Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:



yyyy-MM-ddTHH:mm:ssZ









share|improve this question





























    671















    Given:



    DateTime.UtcNow


    How do I get a string which represents the same value in an ISO 8601-compliant format?



    Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:



    yyyy-MM-ddTHH:mm:ssZ









    share|improve this question



























      671












      671








      671


      117






      Given:



      DateTime.UtcNow


      How do I get a string which represents the same value in an ISO 8601-compliant format?



      Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:



      yyyy-MM-ddTHH:mm:ssZ









      share|improve this question
















      Given:



      DateTime.UtcNow


      How do I get a string which represents the same value in an ISO 8601-compliant format?



      Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:



      yyyy-MM-ddTHH:mm:ssZ






      c# datetime datetime-format iso8601






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 14 '16 at 20:18









      Peter Mortensen

      13.8k1987113




      13.8k1987113










      asked Sep 22 '08 at 13:56









      IainIain

      4,65342013




      4,65342013
























          15 Answers
          15






          active

          oldest

          votes


















          668















          Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.




          DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");


          This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.



          Another way is:



          DateTime.UtcNow.ToString("o");


          which gives you 2008-09-22T14:01:54.9571247Z



          To get the specified format, you can use:



          DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")


          DateTime Formatting Options






          share|improve this answer





















          • 15





            These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

            – Tom Lianza
            Nov 2 '10 at 4:59






          • 9





            I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

            – GONeale
            Aug 3 '11 at 5:50








          • 5





            If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

            – alekop
            Dec 6 '13 at 3:18






          • 4





            The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

            – Gigi
            Aug 29 '14 at 12:50






          • 5





            @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

            – Wayne
            Oct 29 '15 at 17:59



















          304














          DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.






          share|improve this answer





















          • 29





            I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

            – Jon Davis
            Aug 20 '10 at 20:07








          • 17





            While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

            – Henrik
            Jun 26 '12 at 12:05






          • 8





            With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

            – Henrik
            Jun 26 '12 at 12:11






          • 20





            @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

            – binki
            Dec 5 '13 at 18:44






          • 2





            @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

            – drzaus
            Apr 10 '14 at 21:02





















          65














          DateTime.UtcNow.ToString("s")


          Returns something like 2008-04-10T06:30:00



          UtcNow obviously returns a UTC time so there is no harm in:



          string.Concat(DateTime.UtcNow.ToString("s"), "Z")





          share|improve this answer





















          • 10





            Just out of interest: Why string.Concat() rather than '+'?

            – Daniel Fortunov
            Sep 22 '08 at 14:53






          • 4





            There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

            – Koen Zomers
            Jan 24 '12 at 20:52






          • 73





            @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

            – Mark Byers
            Jan 25 '12 at 13:54








          • 63





            Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

            – Noldorin
            Feb 14 '12 at 14:03






          • 5





            @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

            – mrówa
            Sep 17 '14 at 15:55



















          27














          Use:



          private void TimeFormats()
          {
          DateTime localTime = DateTime.Now;
          DateTime utcTime = DateTime.UtcNow;
          DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

          //UTC
          string strUtcTime_o = utcTime.ToString("o");
          string strUtcTime_s = utcTime.ToString("s");
          string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

          //Local
          string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
          string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
          string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

          //Output
          Response.Write("<br/>UTC<br/>");
          Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
          Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
          Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

          Response.Write("<br/>Local Time<br/>");
          Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
          Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
          Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

          }


          OUTPUT



          UTC
          strUtcTime_o: 2012-09-17T22:02:51.4021600Z
          strUtcTime_s: 2012-09-17T22:02:51
          strUtcTime_custom: 2012-09-17T22:02:51Z

          Local Time
          strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
          strLocalTimeAndOffset_s: 2012-09-17T15:02:51
          strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z


          Sources:




          • Standard Date and Time Format Strings (MSDN)


          • Custom Date and Time Format Strings (MSDN)







          share|improve this answer





















          • 2





            seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

            – Holly
            Apr 29 '15 at 9:42





















          21














          System.DateTime.UtcNow.ToString("o")


          =>



          val it : string = "2013-10-13T13:03:50.2950037Z"





          share|improve this answer


























          • Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

            – Matt Wilko
            Sep 1 '15 at 15:54



















          19














          If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,



          2015-07-06T12:08:27


          However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:




          DateTime has countless traps in it that are designed to give your code bugs:



          1.- DateTime values with DateTimeKind.Unspecified are bad news.



          2.- DateTime doesn't care about UTC/Local when doing comparisons.



          3.- DateTime values are not aware of standard format strings.



          4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.







          share|improve this answer





















          • 2





            ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

            – peterincumbria
            Mar 13 '16 at 15:42








          • 2





            For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

            – Blair Connolly
            Jan 18 '17 at 21:45



















          18














          You can get the "Z" (ISO 8601 UTC) with the next code:



          Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)
          Dim res as String = tmpDate.toString("o") '2009-06-15T13:45:30.0000000Z





          Here is why:



          The ISO 8601 have some different formats:



          DateTimeKind.Local



          2009-06-15T13:45:30.0000000-07:00


          DateTimeKind.Utc



          2009-06-15T13:45:30.0000000Z


          DateTimeKind.Unspecified



          2009-06-15T13:45:30.0000000





          .NET provides us with an enum with those options:



          '2009-06-15T13:45:30.0000000-07:00
          Dim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString("o")

          '2009-06-15T13:45:30.0000000Z
          Dim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString("o")

          '2009-06-15T13:45:30.0000000
          Dim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString("o")


          Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.



          Source: Standard Date and Time Format Strings (MSDN)






          share|improve this answer

































            15














            I would just use XmlConvert:



            XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);


            It will automatically preserve the time zone.






            share|improve this answer


























            • I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

              – muruge
              Mar 26 '12 at 21:32





















            10














            Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:



            System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
            // or
            System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");


            References:




            • ISO 8601 specification


            • "K" Specifier






            share|improve this answer





















            • 11





              Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

              – Søren Boisen
              May 6 '15 at 12:56











            • en.wikipedia.org/wiki/ISO_8601#Times

              – binki
              Feb 15 '18 at 17:33



















            8















            The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".



            When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.




            – from MSDN






            share|improve this answer


























            • So it is okay to use .ToString("s")?

              – AhmetB - Google
              Feb 23 '14 at 21:59











            • I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

              – Amal
              Feb 24 '14 at 7:21





















            8














            To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.



            The following will return the string represention you wanted:



            DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)





            share|improve this answer

































              6














              DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");

              DateTime.Now.ToString("O");


              NOTE: Depending on the conversion you are doing on your end, you will be using the first line (most like it) or the second one.



              Make sure to applied format only at local time, since "zzz" is the time zone information for UTC conversion.



              image






              share|improve this answer





















              • 1





                How did you get the clever suggestions for format?

                – Tomáš Zato
                Oct 16 '18 at 15:07











              • based on experience...

                – PSM
                Nov 15 '18 at 17:07






              • 1





                He's asking about the intellisense dropdown...

                – Chris Hynes
                Nov 16 '18 at 12:59











              • I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                – PSM
                Nov 18 '18 at 3:11



















              5














              It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.



              Also it is interesting that "S" format is slow on Classic and fast on Core...



              Of course numbers are very close, between some rows difference is insignificant (tests with suffix _Verify are the same as those that are without that suffix, demonstrates results repeatability)



              BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
              Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
              Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
              [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
              Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
              Core : .NET Core 4.6.25009.03, 64bit RyuJIT


              Method | Job | Runtime | Mean | Error | StdDev | Median | Min | Max | Rank | Gen 0 | Allocated |
              --------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
              CustomDev1 | Clr | Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns | 8 | 0.1086 | 424 B |
              CustomDev2 | Clr | Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns | 7 | 0.1165 | 424 B |
              CustomDev2WithMS | Clr | Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns | 10 | 0.1625 | 592 B |
              FormatO | Clr | Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns | 14 | 0.2897 | 976 B |
              FormatS | Clr | Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns | 13 | 0.2865 | 984 B |
              FormatS_Verify | Clr | Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns | 12 | 0.2885 | 984 B |
              CustomFormatK | Clr | Clr | 912.2 ns | 17.915 ns | 18.398 ns | 916.6 ns | 878.3 ns | 934.1 ns | 4 | 0.0629 | 240 B |
              CustomFormatK_Verify | Clr | Clr | 894.0 ns | 3.877 ns | 3.626 ns | 893.8 ns | 885.1 ns | 900.0 ns | 3 | 0.0636 | 240 B |
              CustomDev1 | Core | Core | 989.1 ns | 12.550 ns | 11.739 ns | 983.8 ns | 976.8 ns | 1,015.5 ns | 6 | 0.1101 | 423 B |
              CustomDev2 | Core | Core | 964.3 ns | 18.826 ns | 23.809 ns | 954.1 ns | 935.5 ns | 1,015.6 ns | 5 | 0.1267 | 423 B |
              CustomDev2WithMS | Core | Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns | 9 | 0.1752 | 590 B |
              FormatO | Core | Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns | 11 | 0.0656 | 271 B |
              FormatS | Core | Core | 993.5 ns | 19.272 ns | 24.372 ns | 999.4 ns | 954.2 ns | 1,029.5 ns | 6 | 0.0633 | 279 B |
              FormatS_Verify | Core | Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns | 976.1 ns | 1,024.3 ns | 6 | 0.0674 | 279 B |
              CustomFormatK | Core | Core | 878.2 ns | 17.017 ns | 20.898 ns | 877.7 ns | 851.4 ns | 928.1 ns | 2 | 0.0555 | 215 B |
              CustomFormatK_Verify | Core | Core | 863.6 ns | 3.968 ns | 3.712 ns | 863.0 ns | 858.6 ns | 870.8 ns | 1 | 0.0550 | 215 B |


              Code:



                  public class BenchmarkDateTimeFormat
              {
              public static DateTime dateTime = DateTime.Now;

              [Benchmark]
              public string CustomDev1()
              {
              var d = dateTime.ToUniversalTime();
              var sb = new StringBuilder(20);

              sb.Append(d.Year).Append("-");
              if (d.Month <= 9)
              sb.Append("0");
              sb.Append(d.Month).Append("-");
              if (d.Day <= 9)
              sb.Append("0");
              sb.Append(d.Day).Append("T");
              if (d.Hour <= 9)
              sb.Append("0");
              sb.Append(d.Hour).Append(":");
              if (d.Minute <= 9)
              sb.Append("0");
              sb.Append(d.Minute).Append(":");
              if (d.Second <= 9)
              sb.Append("0");
              sb.Append(d.Second).Append("Z");
              var text = sb.ToString();
              return text;
              }

              [Benchmark]
              public string CustomDev2()
              {
              var u = dateTime.ToUniversalTime();
              var sb = new StringBuilder(20);
              var y = u.Year;
              var d = u.Day;
              var M = u.Month;
              var h = u.Hour;
              var m = u.Minute;
              var s = u.Second;
              sb.Append(y).Append("-");
              if (M <= 9)
              sb.Append("0");
              sb.Append(M).Append("-");
              if (d <= 9)
              sb.Append("0");
              sb.Append(d).Append("T");
              if (h <= 9)
              sb.Append("0");
              sb.Append(h).Append(":");
              if (m <= 9)
              sb.Append("0");
              sb.Append(m).Append(":");
              if (s <= 9)
              sb.Append("0");
              sb.Append(s).Append("Z");
              var text = sb.ToString();
              return text;
              }

              [Benchmark]
              public string CustomDev2WithMS()
              {
              var u = dateTime.ToUniversalTime();
              var sb = new StringBuilder(23);
              var y = u.Year;
              var d = u.Day;
              var M = u.Month;
              var h = u.Hour;
              var m = u.Minute;
              var s = u.Second;
              var ms = u.Millisecond;
              sb.Append(y).Append("-");
              if (M <= 9)
              sb.Append("0");
              sb.Append(M).Append("-");
              if (d <= 9)
              sb.Append("0");
              sb.Append(d).Append("T");
              if (h <= 9)
              sb.Append("0");
              sb.Append(h).Append(":");
              if (m <= 9)
              sb.Append("0");
              sb.Append(m).Append(":");
              if (s <= 9)
              sb.Append("0");
              sb.Append(s).Append(".");
              sb.Append(ms).Append("Z");
              var text = sb.ToString();
              return text;
              }
              [Benchmark]
              public string FormatO()
              {
              var text = dateTime.ToUniversalTime().ToString("o");
              return text;
              }
              [Benchmark]
              public string FormatS()
              {
              var text = string.Concat(dateTime.ToUniversalTime().ToString("s"),"Z");
              return text;
              }

              [Benchmark]
              public string FormatS_Verify()
              {
              var text = string.Concat(dateTime.ToUniversalTime().ToString("s"), "Z");
              return text;
              }

              [Benchmark]
              public string CustomFormatK()
              {
              var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
              return text;
              }

              [Benchmark]
              public string CustomFormatK_Verify()
              {
              var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
              return text;
              }
              }


              https://github.com/dotnet/BenchmarkDotNet was used






              share|improve this answer

































                1














                If you're developing under SharePoint 2010 or higher you can use



                using Microsoft.SharePoint;
                using Microsoft.SharePoint.Utilities;
                ...
                string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)





                share|improve this answer





















                • 18





                  SharePoint, when your .Net isn't Java enough.

                  – Henrik
                  Feb 27 '15 at 15:30






                • 16





                  Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                  – nathanchere
                  Jun 29 '15 at 8:27











                • Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                  – binki
                  Feb 15 '18 at 17:34



















                1














                To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:



                public static string FormatDateTime(DateTime dateTime)
                {
                return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                }





                share|improve this answer
























                • I think this ISO date string is culture invariant per definition.

                  – Jonas
                  Feb 25 at 12:28












                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f114983%2fgiven-a-datetime-object-how-do-i-get-an-iso-8601-date-in-string-format%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                15 Answers
                15






                active

                oldest

                votes








                15 Answers
                15






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                668















                Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.




                DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");


                This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.



                Another way is:



                DateTime.UtcNow.ToString("o");


                which gives you 2008-09-22T14:01:54.9571247Z



                To get the specified format, you can use:



                DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")


                DateTime Formatting Options






                share|improve this answer





















                • 15





                  These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

                  – Tom Lianza
                  Nov 2 '10 at 4:59






                • 9





                  I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

                  – GONeale
                  Aug 3 '11 at 5:50








                • 5





                  If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

                  – alekop
                  Dec 6 '13 at 3:18






                • 4





                  The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

                  – Gigi
                  Aug 29 '14 at 12:50






                • 5





                  @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

                  – Wayne
                  Oct 29 '15 at 17:59
















                668















                Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.




                DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");


                This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.



                Another way is:



                DateTime.UtcNow.ToString("o");


                which gives you 2008-09-22T14:01:54.9571247Z



                To get the specified format, you can use:



                DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")


                DateTime Formatting Options






                share|improve this answer





















                • 15





                  These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

                  – Tom Lianza
                  Nov 2 '10 at 4:59






                • 9





                  I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

                  – GONeale
                  Aug 3 '11 at 5:50








                • 5





                  If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

                  – alekop
                  Dec 6 '13 at 3:18






                • 4





                  The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

                  – Gigi
                  Aug 29 '14 at 12:50






                • 5





                  @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

                  – Wayne
                  Oct 29 '15 at 17:59














                668












                668








                668








                Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.




                DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");


                This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.



                Another way is:



                DateTime.UtcNow.ToString("o");


                which gives you 2008-09-22T14:01:54.9571247Z



                To get the specified format, you can use:



                DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")


                DateTime Formatting Options






                share|improve this answer
















                Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.




                DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");


                This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.



                Another way is:



                DateTime.UtcNow.ToString("o");


                which gives you 2008-09-22T14:01:54.9571247Z



                To get the specified format, you can use:



                DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")


                DateTime Formatting Options







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 5 at 9:51









                Phil

                4,48523459




                4,48523459










                answered Sep 22 '08 at 14:00









                WayneWayne

                27.6k43348




                27.6k43348








                • 15





                  These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

                  – Tom Lianza
                  Nov 2 '10 at 4:59






                • 9





                  I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

                  – GONeale
                  Aug 3 '11 at 5:50








                • 5





                  If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

                  – alekop
                  Dec 6 '13 at 3:18






                • 4





                  The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

                  – Gigi
                  Aug 29 '14 at 12:50






                • 5





                  @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

                  – Wayne
                  Oct 29 '15 at 17:59














                • 15





                  These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

                  – Tom Lianza
                  Nov 2 '10 at 4:59






                • 9





                  I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

                  – GONeale
                  Aug 3 '11 at 5:50








                • 5





                  If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

                  – alekop
                  Dec 6 '13 at 3:18






                • 4





                  The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

                  – Gigi
                  Aug 29 '14 at 12:50






                • 5





                  @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

                  – Wayne
                  Oct 29 '15 at 17:59








                15




                15





                These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

                – Tom Lianza
                Nov 2 '10 at 4:59





                These days, doing that (trying to render a UTC time with an offset, which doesn't make a lot of sense) throws an exception. So, I agree with the others that the "s" format with the invariant culture is probably more correct. FYI the formatexception's message is: "A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output."

                – Tom Lianza
                Nov 2 '10 at 4:59




                9




                9





                I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

                – GONeale
                Aug 3 '11 at 5:50







                I live in Australia, and for me I had to use ToString("yyyy-MM-ddTHH:mm:ssK") for this to work (with the jquery timeago plugin I was using).

                – GONeale
                Aug 3 '11 at 5:50






                5




                5





                If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

                – alekop
                Dec 6 '13 at 3:18





                If you want to include the timezone offset, do this: dt.ToString("s") + dt.ToString("zzz") // 2013-12-05T07:19:04-08:00

                – alekop
                Dec 6 '13 at 3:18




                4




                4





                The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

                – Gigi
                Aug 29 '14 at 12:50





                The slashes (:) cause issues with the string... put in an @ character to use a string literal instead.

                – Gigi
                Aug 29 '14 at 12:50




                5




                5





                @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

                – Wayne
                Oct 29 '15 at 17:59





                @core: that's one of the standard Formats, which is different from the custom Formats linked: msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

                – Wayne
                Oct 29 '15 at 17:59













                304














                DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.






                share|improve this answer





















                • 29





                  I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

                  – Jon Davis
                  Aug 20 '10 at 20:07








                • 17





                  While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

                  – Henrik
                  Jun 26 '12 at 12:05






                • 8





                  With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

                  – Henrik
                  Jun 26 '12 at 12:11






                • 20





                  @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

                  – binki
                  Dec 5 '13 at 18:44






                • 2





                  @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

                  – drzaus
                  Apr 10 '14 at 21:02


















                304














                DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.






                share|improve this answer





















                • 29





                  I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

                  – Jon Davis
                  Aug 20 '10 at 20:07








                • 17





                  While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

                  – Henrik
                  Jun 26 '12 at 12:05






                • 8





                  With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

                  – Henrik
                  Jun 26 '12 at 12:11






                • 20





                  @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

                  – binki
                  Dec 5 '13 at 18:44






                • 2





                  @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

                  – drzaus
                  Apr 10 '14 at 21:02
















                304












                304








                304







                DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.






                share|improve this answer















                DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 14 '16 at 20:19









                Peter Mortensen

                13.8k1987113




                13.8k1987113










                answered Sep 22 '08 at 14:06









                Simon WilsonSimon Wilson

                6,80832323




                6,80832323








                • 29





                  I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

                  – Jon Davis
                  Aug 20 '10 at 20:07








                • 17





                  While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

                  – Henrik
                  Jun 26 '12 at 12:05






                • 8





                  With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

                  – Henrik
                  Jun 26 '12 at 12:11






                • 20





                  @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

                  – binki
                  Dec 5 '13 at 18:44






                • 2





                  @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

                  – drzaus
                  Apr 10 '14 at 21:02
















                • 29





                  I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

                  – Jon Davis
                  Aug 20 '10 at 20:07








                • 17





                  While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

                  – Henrik
                  Jun 26 '12 at 12:05






                • 8





                  With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

                  – Henrik
                  Jun 26 '12 at 12:11






                • 20





                  @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

                  – binki
                  Dec 5 '13 at 18:44






                • 2





                  @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

                  – drzaus
                  Apr 10 '14 at 21:02










                29




                29





                I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

                – Jon Davis
                Aug 20 '10 at 20:07







                I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use: DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern); However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. "yyyy-MM-ddTHH:mm:ss.fffZ"

                – Jon Davis
                Aug 20 '10 at 20:07






                17




                17





                While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

                – Henrik
                Jun 26 '12 at 12:05





                While it conforms, it leaves out the timezone, Z, looking like this: DateTime.UtcNow.ToString(c, CultureInfo.InvariantCulture)) => 2012-06-26T11:55:36 and there's no millisecond resolution that is very nice to have since computers do a fair number of ticks per second.

                – Henrik
                Jun 26 '12 at 12:05




                8




                8





                With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

                – Henrik
                Jun 26 '12 at 12:11





                With o you get 2012-06-26T11:55:36.1007668Z meaning 36.1007668 seconds, so you get resolution down to 1/10^7 of a second. From ISO8601:2004 If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign [...] the comma (,) or full stop (.)

                – Henrik
                Jun 26 '12 at 12:11




                20




                20





                @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

                – binki
                Dec 5 '13 at 18:44





                @stimpy77 Specifying CultureInfo for "s" makes no sense because: “"O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures.”

                – binki
                Dec 5 '13 at 18:44




                2




                2





                @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

                – drzaus
                Apr 10 '14 at 21:02







                @binki - now I'm very confused. According to the documentation I linked earlier for SortableDateTimePattern, it says it should be culture specific. HOWEVER, it seems to be contradicted by its own examples (since they all look the same); try DateTime.Now.ToString("s", new CultureInfo(myCulture)).

                – drzaus
                Apr 10 '14 at 21:02













                65














                DateTime.UtcNow.ToString("s")


                Returns something like 2008-04-10T06:30:00



                UtcNow obviously returns a UTC time so there is no harm in:



                string.Concat(DateTime.UtcNow.ToString("s"), "Z")





                share|improve this answer





















                • 10





                  Just out of interest: Why string.Concat() rather than '+'?

                  – Daniel Fortunov
                  Sep 22 '08 at 14:53






                • 4





                  There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

                  – Koen Zomers
                  Jan 24 '12 at 20:52






                • 73





                  @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

                  – Mark Byers
                  Jan 25 '12 at 13:54








                • 63





                  Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

                  – Noldorin
                  Feb 14 '12 at 14:03






                • 5





                  @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

                  – mrówa
                  Sep 17 '14 at 15:55
















                65














                DateTime.UtcNow.ToString("s")


                Returns something like 2008-04-10T06:30:00



                UtcNow obviously returns a UTC time so there is no harm in:



                string.Concat(DateTime.UtcNow.ToString("s"), "Z")





                share|improve this answer





















                • 10





                  Just out of interest: Why string.Concat() rather than '+'?

                  – Daniel Fortunov
                  Sep 22 '08 at 14:53






                • 4





                  There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

                  – Koen Zomers
                  Jan 24 '12 at 20:52






                • 73





                  @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

                  – Mark Byers
                  Jan 25 '12 at 13:54








                • 63





                  Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

                  – Noldorin
                  Feb 14 '12 at 14:03






                • 5





                  @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

                  – mrówa
                  Sep 17 '14 at 15:55














                65












                65








                65







                DateTime.UtcNow.ToString("s")


                Returns something like 2008-04-10T06:30:00



                UtcNow obviously returns a UTC time so there is no harm in:



                string.Concat(DateTime.UtcNow.ToString("s"), "Z")





                share|improve this answer















                DateTime.UtcNow.ToString("s")


                Returns something like 2008-04-10T06:30:00



                UtcNow obviously returns a UTC time so there is no harm in:



                string.Concat(DateTime.UtcNow.ToString("s"), "Z")






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Apr 23 '15 at 16:36









                Peter Mortensen

                13.8k1987113




                13.8k1987113










                answered Sep 22 '08 at 13:59









                IainIain

                4,65342013




                4,65342013








                • 10





                  Just out of interest: Why string.Concat() rather than '+'?

                  – Daniel Fortunov
                  Sep 22 '08 at 14:53






                • 4





                  There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

                  – Koen Zomers
                  Jan 24 '12 at 20:52






                • 73





                  @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

                  – Mark Byers
                  Jan 25 '12 at 13:54








                • 63





                  Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

                  – Noldorin
                  Feb 14 '12 at 14:03






                • 5





                  @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

                  – mrówa
                  Sep 17 '14 at 15:55














                • 10





                  Just out of interest: Why string.Concat() rather than '+'?

                  – Daniel Fortunov
                  Sep 22 '08 at 14:53






                • 4





                  There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

                  – Koen Zomers
                  Jan 24 '12 at 20:52






                • 73





                  @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

                  – Mark Byers
                  Jan 25 '12 at 13:54








                • 63





                  Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

                  – Noldorin
                  Feb 14 '12 at 14:03






                • 5





                  @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

                  – mrówa
                  Sep 17 '14 at 15:55








                10




                10





                Just out of interest: Why string.Concat() rather than '+'?

                – Daniel Fortunov
                Sep 22 '08 at 14:53





                Just out of interest: Why string.Concat() rather than '+'?

                – Daniel Fortunov
                Sep 22 '08 at 14:53




                4




                4





                There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

                – Koen Zomers
                Jan 24 '12 at 20:52





                There sure is a difference. When using a + to concatenate strings, in memory three chunks of memory are reserved to store the strings: one for the first, one for the second and one for the complete string. Always use string.Concat and string.Format as these are much more memory preservative and only reserve one chunk of memory.

                – Koen Zomers
                Jan 24 '12 at 20:52




                73




                73





                @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

                – Mark Byers
                Jan 25 '12 at 13:54







                @KoenZomers: I don't think that's correct. I think a + b compiles to the same intermediate code as string.Concat(a, b) (assuming that a and b are strings, of course) so there is no difference in performance or memory consumption.

                – Mark Byers
                Jan 25 '12 at 13:54






                63




                63





                Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

                – Noldorin
                Feb 14 '12 at 14:03





                Yes, Mark is correct. Koen, you have just fallen into the trap of an absurdly premature micro-optimisation, even if you are correct.

                – Noldorin
                Feb 14 '12 at 14:03




                5




                5





                @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

                – mrówa
                Sep 17 '14 at 15:55





                @greg84: Well, you are not entirely right. Look at this post by Microsoft architect Rico Mariani: blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx - he says a + b does compile to concat + there's some more information about proper usage of StringBuilder.

                – mrówa
                Sep 17 '14 at 15:55











                27














                Use:



                private void TimeFormats()
                {
                DateTime localTime = DateTime.Now;
                DateTime utcTime = DateTime.UtcNow;
                DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

                //UTC
                string strUtcTime_o = utcTime.ToString("o");
                string strUtcTime_s = utcTime.ToString("s");
                string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Local
                string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
                string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
                string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Output
                Response.Write("<br/>UTC<br/>");
                Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
                Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
                Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

                Response.Write("<br/>Local Time<br/>");
                Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
                Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
                Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

                }


                OUTPUT



                UTC
                strUtcTime_o: 2012-09-17T22:02:51.4021600Z
                strUtcTime_s: 2012-09-17T22:02:51
                strUtcTime_custom: 2012-09-17T22:02:51Z

                Local Time
                strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
                strLocalTimeAndOffset_s: 2012-09-17T15:02:51
                strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z


                Sources:




                • Standard Date and Time Format Strings (MSDN)


                • Custom Date and Time Format Strings (MSDN)







                share|improve this answer





















                • 2





                  seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

                  – Holly
                  Apr 29 '15 at 9:42


















                27














                Use:



                private void TimeFormats()
                {
                DateTime localTime = DateTime.Now;
                DateTime utcTime = DateTime.UtcNow;
                DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

                //UTC
                string strUtcTime_o = utcTime.ToString("o");
                string strUtcTime_s = utcTime.ToString("s");
                string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Local
                string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
                string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
                string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Output
                Response.Write("<br/>UTC<br/>");
                Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
                Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
                Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

                Response.Write("<br/>Local Time<br/>");
                Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
                Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
                Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

                }


                OUTPUT



                UTC
                strUtcTime_o: 2012-09-17T22:02:51.4021600Z
                strUtcTime_s: 2012-09-17T22:02:51
                strUtcTime_custom: 2012-09-17T22:02:51Z

                Local Time
                strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
                strLocalTimeAndOffset_s: 2012-09-17T15:02:51
                strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z


                Sources:




                • Standard Date and Time Format Strings (MSDN)


                • Custom Date and Time Format Strings (MSDN)







                share|improve this answer





















                • 2





                  seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

                  – Holly
                  Apr 29 '15 at 9:42
















                27












                27








                27







                Use:



                private void TimeFormats()
                {
                DateTime localTime = DateTime.Now;
                DateTime utcTime = DateTime.UtcNow;
                DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

                //UTC
                string strUtcTime_o = utcTime.ToString("o");
                string strUtcTime_s = utcTime.ToString("s");
                string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Local
                string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
                string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
                string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Output
                Response.Write("<br/>UTC<br/>");
                Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
                Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
                Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

                Response.Write("<br/>Local Time<br/>");
                Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
                Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
                Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

                }


                OUTPUT



                UTC
                strUtcTime_o: 2012-09-17T22:02:51.4021600Z
                strUtcTime_s: 2012-09-17T22:02:51
                strUtcTime_custom: 2012-09-17T22:02:51Z

                Local Time
                strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
                strLocalTimeAndOffset_s: 2012-09-17T15:02:51
                strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z


                Sources:




                • Standard Date and Time Format Strings (MSDN)


                • Custom Date and Time Format Strings (MSDN)







                share|improve this answer















                Use:



                private void TimeFormats()
                {
                DateTime localTime = DateTime.Now;
                DateTime utcTime = DateTime.UtcNow;
                DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));

                //UTC
                string strUtcTime_o = utcTime.ToString("o");
                string strUtcTime_s = utcTime.ToString("s");
                string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Local
                string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
                string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
                string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");

                //Output
                Response.Write("<br/>UTC<br/>");
                Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
                Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
                Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");

                Response.Write("<br/>Local Time<br/>");
                Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
                Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
                Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");

                }


                OUTPUT



                UTC
                strUtcTime_o: 2012-09-17T22:02:51.4021600Z
                strUtcTime_s: 2012-09-17T22:02:51
                strUtcTime_custom: 2012-09-17T22:02:51Z

                Local Time
                strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
                strLocalTimeAndOffset_s: 2012-09-17T15:02:51
                strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z


                Sources:




                • Standard Date and Time Format Strings (MSDN)


                • Custom Date and Time Format Strings (MSDN)








                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 26 '18 at 9:01









                Kolappan Nathan

                57611320




                57611320










                answered Sep 17 '12 at 22:10









                DonDon

                47953




                47953








                • 2





                  seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

                  – Holly
                  Apr 29 '15 at 9:42
















                • 2





                  seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

                  – Holly
                  Apr 29 '15 at 9:42










                2




                2





                seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

                – Holly
                Apr 29 '15 at 9:42







                seems you are a victim of copying at local custom ;-) string strLocalTimeAndOffset_custom = localTimeAndOffset.ToString("yyyy-MM-ddTHH:mm:ssK"); would result in: strLocalTimeAndOffset_custom: 2012-09-17T22:02:51-07:00

                – Holly
                Apr 29 '15 at 9:42













                21














                System.DateTime.UtcNow.ToString("o")


                =>



                val it : string = "2013-10-13T13:03:50.2950037Z"





                share|improve this answer


























                • Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

                  – Matt Wilko
                  Sep 1 '15 at 15:54
















                21














                System.DateTime.UtcNow.ToString("o")


                =>



                val it : string = "2013-10-13T13:03:50.2950037Z"





                share|improve this answer


























                • Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

                  – Matt Wilko
                  Sep 1 '15 at 15:54














                21












                21








                21







                System.DateTime.UtcNow.ToString("o")


                =>



                val it : string = "2013-10-13T13:03:50.2950037Z"





                share|improve this answer















                System.DateTime.UtcNow.ToString("o")


                =>



                val it : string = "2013-10-13T13:03:50.2950037Z"






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 13 '13 at 17:14

























                answered Oct 13 '13 at 13:05









                HenrikHenrik

                6,89744273




                6,89744273













                • Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

                  – Matt Wilko
                  Sep 1 '15 at 15:54



















                • Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

                  – Matt Wilko
                  Sep 1 '15 at 15:54

















                Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

                – Matt Wilko
                Sep 1 '15 at 15:54





                Agreed this is the only way to be absolutely sure that you have an unambiguous date/time across any timezone

                – Matt Wilko
                Sep 1 '15 at 15:54











                19














                If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,



                2015-07-06T12:08:27


                However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:




                DateTime has countless traps in it that are designed to give your code bugs:



                1.- DateTime values with DateTimeKind.Unspecified are bad news.



                2.- DateTime doesn't care about UTC/Local when doing comparisons.



                3.- DateTime values are not aware of standard format strings.



                4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.







                share|improve this answer





















                • 2





                  ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

                  – peterincumbria
                  Mar 13 '16 at 15:42








                • 2





                  For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

                  – Blair Connolly
                  Jan 18 '17 at 21:45
















                19














                If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,



                2015-07-06T12:08:27


                However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:




                DateTime has countless traps in it that are designed to give your code bugs:



                1.- DateTime values with DateTimeKind.Unspecified are bad news.



                2.- DateTime doesn't care about UTC/Local when doing comparisons.



                3.- DateTime values are not aware of standard format strings.



                4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.







                share|improve this answer





















                • 2





                  ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

                  – peterincumbria
                  Mar 13 '16 at 15:42








                • 2





                  For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

                  – Blair Connolly
                  Jan 18 '17 at 21:45














                19












                19








                19







                If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,



                2015-07-06T12:08:27


                However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:




                DateTime has countless traps in it that are designed to give your code bugs:



                1.- DateTime values with DateTimeKind.Unspecified are bad news.



                2.- DateTime doesn't care about UTC/Local when doing comparisons.



                3.- DateTime values are not aware of standard format strings.



                4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.







                share|improve this answer















                If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,



                2015-07-06T12:08:27


                However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:




                DateTime has countless traps in it that are designed to give your code bugs:



                1.- DateTime values with DateTimeKind.Unspecified are bad news.



                2.- DateTime doesn't care about UTC/Local when doing comparisons.



                3.- DateTime values are not aware of standard format strings.



                4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.








                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 14 '16 at 20:22









                Peter Mortensen

                13.8k1987113




                13.8k1987113










                answered Jul 6 '15 at 16:11









                Alex NolascoAlex Nolasco

                14.1k85863




                14.1k85863








                • 2





                  ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

                  – peterincumbria
                  Mar 13 '16 at 15:42








                • 2





                  For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

                  – Blair Connolly
                  Jan 18 '17 at 21:45














                • 2





                  ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

                  – peterincumbria
                  Mar 13 '16 at 15:42








                • 2





                  For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

                  – Blair Connolly
                  Jan 18 '17 at 21:45








                2




                2





                ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

                – peterincumbria
                Mar 13 '16 at 15:42







                ISO8601 is used in strava for one. However please use:StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ") rather than ToString("o") which adds milliseconds etc.

                – peterincumbria
                Mar 13 '16 at 15:42






                2




                2





                For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

                – Blair Connolly
                Jan 18 '17 at 21:45





                For me, "yyyy-MM-dd-THH:mm:ssZ" literally outputted "Z" at the end of my string instead of a timezone marker, which did not do what I wanted. ToString("o") actually did what I needed, much easier and shorter.

                – Blair Connolly
                Jan 18 '17 at 21:45











                18














                You can get the "Z" (ISO 8601 UTC) with the next code:



                Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)
                Dim res as String = tmpDate.toString("o") '2009-06-15T13:45:30.0000000Z





                Here is why:



                The ISO 8601 have some different formats:



                DateTimeKind.Local



                2009-06-15T13:45:30.0000000-07:00


                DateTimeKind.Utc



                2009-06-15T13:45:30.0000000Z


                DateTimeKind.Unspecified



                2009-06-15T13:45:30.0000000





                .NET provides us with an enum with those options:



                '2009-06-15T13:45:30.0000000-07:00
                Dim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString("o")

                '2009-06-15T13:45:30.0000000Z
                Dim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString("o")

                '2009-06-15T13:45:30.0000000
                Dim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString("o")


                Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.



                Source: Standard Date and Time Format Strings (MSDN)






                share|improve this answer






























                  18














                  You can get the "Z" (ISO 8601 UTC) with the next code:



                  Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)
                  Dim res as String = tmpDate.toString("o") '2009-06-15T13:45:30.0000000Z





                  Here is why:



                  The ISO 8601 have some different formats:



                  DateTimeKind.Local



                  2009-06-15T13:45:30.0000000-07:00


                  DateTimeKind.Utc



                  2009-06-15T13:45:30.0000000Z


                  DateTimeKind.Unspecified



                  2009-06-15T13:45:30.0000000





                  .NET provides us with an enum with those options:



                  '2009-06-15T13:45:30.0000000-07:00
                  Dim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString("o")

                  '2009-06-15T13:45:30.0000000Z
                  Dim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString("o")

                  '2009-06-15T13:45:30.0000000
                  Dim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString("o")


                  Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.



                  Source: Standard Date and Time Format Strings (MSDN)






                  share|improve this answer




























                    18












                    18








                    18







                    You can get the "Z" (ISO 8601 UTC) with the next code:



                    Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)
                    Dim res as String = tmpDate.toString("o") '2009-06-15T13:45:30.0000000Z





                    Here is why:



                    The ISO 8601 have some different formats:



                    DateTimeKind.Local



                    2009-06-15T13:45:30.0000000-07:00


                    DateTimeKind.Utc



                    2009-06-15T13:45:30.0000000Z


                    DateTimeKind.Unspecified



                    2009-06-15T13:45:30.0000000





                    .NET provides us with an enum with those options:



                    '2009-06-15T13:45:30.0000000-07:00
                    Dim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString("o")

                    '2009-06-15T13:45:30.0000000Z
                    Dim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString("o")

                    '2009-06-15T13:45:30.0000000
                    Dim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString("o")


                    Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.



                    Source: Standard Date and Time Format Strings (MSDN)






                    share|improve this answer















                    You can get the "Z" (ISO 8601 UTC) with the next code:



                    Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)
                    Dim res as String = tmpDate.toString("o") '2009-06-15T13:45:30.0000000Z





                    Here is why:



                    The ISO 8601 have some different formats:



                    DateTimeKind.Local



                    2009-06-15T13:45:30.0000000-07:00


                    DateTimeKind.Utc



                    2009-06-15T13:45:30.0000000Z


                    DateTimeKind.Unspecified



                    2009-06-15T13:45:30.0000000





                    .NET provides us with an enum with those options:



                    '2009-06-15T13:45:30.0000000-07:00
                    Dim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString("o")

                    '2009-06-15T13:45:30.0000000Z
                    Dim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString("o")

                    '2009-06-15T13:45:30.0000000
                    Dim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString("o")


                    Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.



                    Source: Standard Date and Time Format Strings (MSDN)







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 13 '16 at 11:06









                    Peter Mortensen

                    13.8k1987113




                    13.8k1987113










                    answered Sep 17 '14 at 14:31









                    OaxasOaxas

                    27937




                    27937























                        15














                        I would just use XmlConvert:



                        XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);


                        It will automatically preserve the time zone.






                        share|improve this answer


























                        • I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

                          – muruge
                          Mar 26 '12 at 21:32


















                        15














                        I would just use XmlConvert:



                        XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);


                        It will automatically preserve the time zone.






                        share|improve this answer


























                        • I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

                          – muruge
                          Mar 26 '12 at 21:32
















                        15












                        15








                        15







                        I would just use XmlConvert:



                        XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);


                        It will automatically preserve the time zone.






                        share|improve this answer















                        I would just use XmlConvert:



                        XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);


                        It will automatically preserve the time zone.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 26 '18 at 11:33









                        Kolappan Nathan

                        57611320




                        57611320










                        answered Jun 2 '11 at 15:19









                        SumrakSumrak

                        2,00262536




                        2,00262536













                        • I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

                          – muruge
                          Mar 26 '12 at 21:32





















                        • I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

                          – muruge
                          Mar 26 '12 at 21:32



















                        I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

                        – muruge
                        Mar 26 '12 at 21:32







                        I went ahead and added an extension method. public static class DateTimeExtensions { public static string ToIsoFormat(this DateTime dateTime) { return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.RoundtripKind); } }

                        – muruge
                        Mar 26 '12 at 21:32













                        10














                        Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:



                        System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                        // or
                        System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");


                        References:




                        • ISO 8601 specification


                        • "K" Specifier






                        share|improve this answer





















                        • 11





                          Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

                          – Søren Boisen
                          May 6 '15 at 12:56











                        • en.wikipedia.org/wiki/ISO_8601#Times

                          – binki
                          Feb 15 '18 at 17:33
















                        10














                        Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:



                        System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                        // or
                        System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");


                        References:




                        • ISO 8601 specification


                        • "K" Specifier






                        share|improve this answer





















                        • 11





                          Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

                          – Søren Boisen
                          May 6 '15 at 12:56











                        • en.wikipedia.org/wiki/ISO_8601#Times

                          – binki
                          Feb 15 '18 at 17:33














                        10












                        10








                        10







                        Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:



                        System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                        // or
                        System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");


                        References:




                        • ISO 8601 specification


                        • "K" Specifier






                        share|improve this answer















                        Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:



                        System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                        // or
                        System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");


                        References:




                        • ISO 8601 specification


                        • "K" Specifier







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 26 '18 at 11:34









                        Kolappan Nathan

                        57611320




                        57611320










                        answered Dec 5 '14 at 17:11









                        Justin TurnerJustin Turner

                        33325




                        33325








                        • 11





                          Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

                          – Søren Boisen
                          May 6 '15 at 12:56











                        • en.wikipedia.org/wiki/ISO_8601#Times

                          – binki
                          Feb 15 '18 at 17:33














                        • 11





                          Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

                          – Søren Boisen
                          May 6 '15 at 12:56











                        • en.wikipedia.org/wiki/ISO_8601#Times

                          – binki
                          Feb 15 '18 at 17:33








                        11




                        11





                        Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

                        – Søren Boisen
                        May 6 '15 at 12:56





                        Read your own Wikipedia link under "Times". It mentions "Decimal fractions", meaning ISO 8601 supports both milliseconds and microseconds (but communicating parties may limit number of decimal places accepted).

                        – Søren Boisen
                        May 6 '15 at 12:56













                        en.wikipedia.org/wiki/ISO_8601#Times

                        – binki
                        Feb 15 '18 at 17:33





                        en.wikipedia.org/wiki/ISO_8601#Times

                        – binki
                        Feb 15 '18 at 17:33











                        8















                        The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".



                        When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.




                        – from MSDN






                        share|improve this answer


























                        • So it is okay to use .ToString("s")?

                          – AhmetB - Google
                          Feb 23 '14 at 21:59











                        • I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

                          – Amal
                          Feb 24 '14 at 7:21


















                        8















                        The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".



                        When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.




                        – from MSDN






                        share|improve this answer


























                        • So it is okay to use .ToString("s")?

                          – AhmetB - Google
                          Feb 23 '14 at 21:59











                        • I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

                          – Amal
                          Feb 24 '14 at 7:21
















                        8












                        8








                        8








                        The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".



                        When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.




                        – from MSDN






                        share|improve this answer
















                        The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".



                        When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.




                        – from MSDN







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited May 23 '13 at 22:08









                        Rory O'Kane

                        18.8k764108




                        18.8k764108










                        answered Sep 12 '12 at 10:12









                        AmalAmal

                        332512




                        332512













                        • So it is okay to use .ToString("s")?

                          – AhmetB - Google
                          Feb 23 '14 at 21:59











                        • I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

                          – Amal
                          Feb 24 '14 at 7:21





















                        • So it is okay to use .ToString("s")?

                          – AhmetB - Google
                          Feb 23 '14 at 21:59











                        • I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

                          – Amal
                          Feb 24 '14 at 7:21



















                        So it is okay to use .ToString("s")?

                        – AhmetB - Google
                        Feb 23 '14 at 21:59





                        So it is okay to use .ToString("s")?

                        – AhmetB - Google
                        Feb 23 '14 at 21:59













                        I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

                        – Amal
                        Feb 24 '14 at 7:21







                        I believe so. - As long as your requirement matches the original question that is.. But do take a look at the warning by simon wilson below

                        – Amal
                        Feb 24 '14 at 7:21













                        8














                        To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.



                        The following will return the string represention you wanted:



                        DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)





                        share|improve this answer






























                          8














                          To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.



                          The following will return the string represention you wanted:



                          DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)





                          share|improve this answer




























                            8












                            8








                            8







                            To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.



                            The following will return the string represention you wanted:



                            DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)





                            share|improve this answer















                            To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.



                            The following will return the string represention you wanted:



                            DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jun 19 '15 at 8:13









                            Peter Mortensen

                            13.8k1987113




                            13.8k1987113










                            answered Nov 26 '08 at 21:55









                            OppositionalOppositional

                            9,16364259




                            9,16364259























                                6














                                DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");

                                DateTime.Now.ToString("O");


                                NOTE: Depending on the conversion you are doing on your end, you will be using the first line (most like it) or the second one.



                                Make sure to applied format only at local time, since "zzz" is the time zone information for UTC conversion.



                                image






                                share|improve this answer





















                                • 1





                                  How did you get the clever suggestions for format?

                                  – Tomáš Zato
                                  Oct 16 '18 at 15:07











                                • based on experience...

                                  – PSM
                                  Nov 15 '18 at 17:07






                                • 1





                                  He's asking about the intellisense dropdown...

                                  – Chris Hynes
                                  Nov 16 '18 at 12:59











                                • I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                                  – PSM
                                  Nov 18 '18 at 3:11
















                                6














                                DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");

                                DateTime.Now.ToString("O");


                                NOTE: Depending on the conversion you are doing on your end, you will be using the first line (most like it) or the second one.



                                Make sure to applied format only at local time, since "zzz" is the time zone information for UTC conversion.



                                image






                                share|improve this answer





















                                • 1





                                  How did you get the clever suggestions for format?

                                  – Tomáš Zato
                                  Oct 16 '18 at 15:07











                                • based on experience...

                                  – PSM
                                  Nov 15 '18 at 17:07






                                • 1





                                  He's asking about the intellisense dropdown...

                                  – Chris Hynes
                                  Nov 16 '18 at 12:59











                                • I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                                  – PSM
                                  Nov 18 '18 at 3:11














                                6












                                6








                                6







                                DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");

                                DateTime.Now.ToString("O");


                                NOTE: Depending on the conversion you are doing on your end, you will be using the first line (most like it) or the second one.



                                Make sure to applied format only at local time, since "zzz" is the time zone information for UTC conversion.



                                image






                                share|improve this answer















                                DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");

                                DateTime.Now.ToString("O");


                                NOTE: Depending on the conversion you are doing on your end, you will be using the first line (most like it) or the second one.



                                Make sure to applied format only at local time, since "zzz" is the time zone information for UTC conversion.



                                image







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 31 '18 at 16:37

























                                answered Aug 30 '18 at 19:05









                                PSMPSM

                                6116




                                6116








                                • 1





                                  How did you get the clever suggestions for format?

                                  – Tomáš Zato
                                  Oct 16 '18 at 15:07











                                • based on experience...

                                  – PSM
                                  Nov 15 '18 at 17:07






                                • 1





                                  He's asking about the intellisense dropdown...

                                  – Chris Hynes
                                  Nov 16 '18 at 12:59











                                • I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                                  – PSM
                                  Nov 18 '18 at 3:11














                                • 1





                                  How did you get the clever suggestions for format?

                                  – Tomáš Zato
                                  Oct 16 '18 at 15:07











                                • based on experience...

                                  – PSM
                                  Nov 15 '18 at 17:07






                                • 1





                                  He's asking about the intellisense dropdown...

                                  – Chris Hynes
                                  Nov 16 '18 at 12:59











                                • I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                                  – PSM
                                  Nov 18 '18 at 3:11








                                1




                                1





                                How did you get the clever suggestions for format?

                                – Tomáš Zato
                                Oct 16 '18 at 15:07





                                How did you get the clever suggestions for format?

                                – Tomáš Zato
                                Oct 16 '18 at 15:07













                                based on experience...

                                – PSM
                                Nov 15 '18 at 17:07





                                based on experience...

                                – PSM
                                Nov 15 '18 at 17:07




                                1




                                1





                                He's asking about the intellisense dropdown...

                                – Chris Hynes
                                Nov 16 '18 at 12:59





                                He's asking about the intellisense dropdown...

                                – Chris Hynes
                                Nov 16 '18 at 12:59













                                I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                                – PSM
                                Nov 18 '18 at 3:11





                                I'm not so sure #ChrisHynes since he is asking about the suggestion I made regarding the first line of code, but if you are correct and that's the case the answer is "ReSharper"

                                – PSM
                                Nov 18 '18 at 3:11











                                5














                                It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.



                                Also it is interesting that "S" format is slow on Classic and fast on Core...



                                Of course numbers are very close, between some rows difference is insignificant (tests with suffix _Verify are the same as those that are without that suffix, demonstrates results repeatability)



                                BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
                                Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
                                Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
                                [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                Core : .NET Core 4.6.25009.03, 64bit RyuJIT


                                Method | Job | Runtime | Mean | Error | StdDev | Median | Min | Max | Rank | Gen 0 | Allocated |
                                --------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
                                CustomDev1 | Clr | Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns | 8 | 0.1086 | 424 B |
                                CustomDev2 | Clr | Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns | 7 | 0.1165 | 424 B |
                                CustomDev2WithMS | Clr | Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns | 10 | 0.1625 | 592 B |
                                FormatO | Clr | Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns | 14 | 0.2897 | 976 B |
                                FormatS | Clr | Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns | 13 | 0.2865 | 984 B |
                                FormatS_Verify | Clr | Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns | 12 | 0.2885 | 984 B |
                                CustomFormatK | Clr | Clr | 912.2 ns | 17.915 ns | 18.398 ns | 916.6 ns | 878.3 ns | 934.1 ns | 4 | 0.0629 | 240 B |
                                CustomFormatK_Verify | Clr | Clr | 894.0 ns | 3.877 ns | 3.626 ns | 893.8 ns | 885.1 ns | 900.0 ns | 3 | 0.0636 | 240 B |
                                CustomDev1 | Core | Core | 989.1 ns | 12.550 ns | 11.739 ns | 983.8 ns | 976.8 ns | 1,015.5 ns | 6 | 0.1101 | 423 B |
                                CustomDev2 | Core | Core | 964.3 ns | 18.826 ns | 23.809 ns | 954.1 ns | 935.5 ns | 1,015.6 ns | 5 | 0.1267 | 423 B |
                                CustomDev2WithMS | Core | Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns | 9 | 0.1752 | 590 B |
                                FormatO | Core | Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns | 11 | 0.0656 | 271 B |
                                FormatS | Core | Core | 993.5 ns | 19.272 ns | 24.372 ns | 999.4 ns | 954.2 ns | 1,029.5 ns | 6 | 0.0633 | 279 B |
                                FormatS_Verify | Core | Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns | 976.1 ns | 1,024.3 ns | 6 | 0.0674 | 279 B |
                                CustomFormatK | Core | Core | 878.2 ns | 17.017 ns | 20.898 ns | 877.7 ns | 851.4 ns | 928.1 ns | 2 | 0.0555 | 215 B |
                                CustomFormatK_Verify | Core | Core | 863.6 ns | 3.968 ns | 3.712 ns | 863.0 ns | 858.6 ns | 870.8 ns | 1 | 0.0550 | 215 B |


                                Code:



                                    public class BenchmarkDateTimeFormat
                                {
                                public static DateTime dateTime = DateTime.Now;

                                [Benchmark]
                                public string CustomDev1()
                                {
                                var d = dateTime.ToUniversalTime();
                                var sb = new StringBuilder(20);

                                sb.Append(d.Year).Append("-");
                                if (d.Month <= 9)
                                sb.Append("0");
                                sb.Append(d.Month).Append("-");
                                if (d.Day <= 9)
                                sb.Append("0");
                                sb.Append(d.Day).Append("T");
                                if (d.Hour <= 9)
                                sb.Append("0");
                                sb.Append(d.Hour).Append(":");
                                if (d.Minute <= 9)
                                sb.Append("0");
                                sb.Append(d.Minute).Append(":");
                                if (d.Second <= 9)
                                sb.Append("0");
                                sb.Append(d.Second).Append("Z");
                                var text = sb.ToString();
                                return text;
                                }

                                [Benchmark]
                                public string CustomDev2()
                                {
                                var u = dateTime.ToUniversalTime();
                                var sb = new StringBuilder(20);
                                var y = u.Year;
                                var d = u.Day;
                                var M = u.Month;
                                var h = u.Hour;
                                var m = u.Minute;
                                var s = u.Second;
                                sb.Append(y).Append("-");
                                if (M <= 9)
                                sb.Append("0");
                                sb.Append(M).Append("-");
                                if (d <= 9)
                                sb.Append("0");
                                sb.Append(d).Append("T");
                                if (h <= 9)
                                sb.Append("0");
                                sb.Append(h).Append(":");
                                if (m <= 9)
                                sb.Append("0");
                                sb.Append(m).Append(":");
                                if (s <= 9)
                                sb.Append("0");
                                sb.Append(s).Append("Z");
                                var text = sb.ToString();
                                return text;
                                }

                                [Benchmark]
                                public string CustomDev2WithMS()
                                {
                                var u = dateTime.ToUniversalTime();
                                var sb = new StringBuilder(23);
                                var y = u.Year;
                                var d = u.Day;
                                var M = u.Month;
                                var h = u.Hour;
                                var m = u.Minute;
                                var s = u.Second;
                                var ms = u.Millisecond;
                                sb.Append(y).Append("-");
                                if (M <= 9)
                                sb.Append("0");
                                sb.Append(M).Append("-");
                                if (d <= 9)
                                sb.Append("0");
                                sb.Append(d).Append("T");
                                if (h <= 9)
                                sb.Append("0");
                                sb.Append(h).Append(":");
                                if (m <= 9)
                                sb.Append("0");
                                sb.Append(m).Append(":");
                                if (s <= 9)
                                sb.Append("0");
                                sb.Append(s).Append(".");
                                sb.Append(ms).Append("Z");
                                var text = sb.ToString();
                                return text;
                                }
                                [Benchmark]
                                public string FormatO()
                                {
                                var text = dateTime.ToUniversalTime().ToString("o");
                                return text;
                                }
                                [Benchmark]
                                public string FormatS()
                                {
                                var text = string.Concat(dateTime.ToUniversalTime().ToString("s"),"Z");
                                return text;
                                }

                                [Benchmark]
                                public string FormatS_Verify()
                                {
                                var text = string.Concat(dateTime.ToUniversalTime().ToString("s"), "Z");
                                return text;
                                }

                                [Benchmark]
                                public string CustomFormatK()
                                {
                                var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                return text;
                                }

                                [Benchmark]
                                public string CustomFormatK_Verify()
                                {
                                var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                return text;
                                }
                                }


                                https://github.com/dotnet/BenchmarkDotNet was used






                                share|improve this answer






























                                  5














                                  It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.



                                  Also it is interesting that "S" format is slow on Classic and fast on Core...



                                  Of course numbers are very close, between some rows difference is insignificant (tests with suffix _Verify are the same as those that are without that suffix, demonstrates results repeatability)



                                  BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
                                  Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
                                  Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
                                  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                  Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                  Core : .NET Core 4.6.25009.03, 64bit RyuJIT


                                  Method | Job | Runtime | Mean | Error | StdDev | Median | Min | Max | Rank | Gen 0 | Allocated |
                                  --------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
                                  CustomDev1 | Clr | Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns | 8 | 0.1086 | 424 B |
                                  CustomDev2 | Clr | Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns | 7 | 0.1165 | 424 B |
                                  CustomDev2WithMS | Clr | Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns | 10 | 0.1625 | 592 B |
                                  FormatO | Clr | Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns | 14 | 0.2897 | 976 B |
                                  FormatS | Clr | Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns | 13 | 0.2865 | 984 B |
                                  FormatS_Verify | Clr | Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns | 12 | 0.2885 | 984 B |
                                  CustomFormatK | Clr | Clr | 912.2 ns | 17.915 ns | 18.398 ns | 916.6 ns | 878.3 ns | 934.1 ns | 4 | 0.0629 | 240 B |
                                  CustomFormatK_Verify | Clr | Clr | 894.0 ns | 3.877 ns | 3.626 ns | 893.8 ns | 885.1 ns | 900.0 ns | 3 | 0.0636 | 240 B |
                                  CustomDev1 | Core | Core | 989.1 ns | 12.550 ns | 11.739 ns | 983.8 ns | 976.8 ns | 1,015.5 ns | 6 | 0.1101 | 423 B |
                                  CustomDev2 | Core | Core | 964.3 ns | 18.826 ns | 23.809 ns | 954.1 ns | 935.5 ns | 1,015.6 ns | 5 | 0.1267 | 423 B |
                                  CustomDev2WithMS | Core | Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns | 9 | 0.1752 | 590 B |
                                  FormatO | Core | Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns | 11 | 0.0656 | 271 B |
                                  FormatS | Core | Core | 993.5 ns | 19.272 ns | 24.372 ns | 999.4 ns | 954.2 ns | 1,029.5 ns | 6 | 0.0633 | 279 B |
                                  FormatS_Verify | Core | Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns | 976.1 ns | 1,024.3 ns | 6 | 0.0674 | 279 B |
                                  CustomFormatK | Core | Core | 878.2 ns | 17.017 ns | 20.898 ns | 877.7 ns | 851.4 ns | 928.1 ns | 2 | 0.0555 | 215 B |
                                  CustomFormatK_Verify | Core | Core | 863.6 ns | 3.968 ns | 3.712 ns | 863.0 ns | 858.6 ns | 870.8 ns | 1 | 0.0550 | 215 B |


                                  Code:



                                      public class BenchmarkDateTimeFormat
                                  {
                                  public static DateTime dateTime = DateTime.Now;

                                  [Benchmark]
                                  public string CustomDev1()
                                  {
                                  var d = dateTime.ToUniversalTime();
                                  var sb = new StringBuilder(20);

                                  sb.Append(d.Year).Append("-");
                                  if (d.Month <= 9)
                                  sb.Append("0");
                                  sb.Append(d.Month).Append("-");
                                  if (d.Day <= 9)
                                  sb.Append("0");
                                  sb.Append(d.Day).Append("T");
                                  if (d.Hour <= 9)
                                  sb.Append("0");
                                  sb.Append(d.Hour).Append(":");
                                  if (d.Minute <= 9)
                                  sb.Append("0");
                                  sb.Append(d.Minute).Append(":");
                                  if (d.Second <= 9)
                                  sb.Append("0");
                                  sb.Append(d.Second).Append("Z");
                                  var text = sb.ToString();
                                  return text;
                                  }

                                  [Benchmark]
                                  public string CustomDev2()
                                  {
                                  var u = dateTime.ToUniversalTime();
                                  var sb = new StringBuilder(20);
                                  var y = u.Year;
                                  var d = u.Day;
                                  var M = u.Month;
                                  var h = u.Hour;
                                  var m = u.Minute;
                                  var s = u.Second;
                                  sb.Append(y).Append("-");
                                  if (M <= 9)
                                  sb.Append("0");
                                  sb.Append(M).Append("-");
                                  if (d <= 9)
                                  sb.Append("0");
                                  sb.Append(d).Append("T");
                                  if (h <= 9)
                                  sb.Append("0");
                                  sb.Append(h).Append(":");
                                  if (m <= 9)
                                  sb.Append("0");
                                  sb.Append(m).Append(":");
                                  if (s <= 9)
                                  sb.Append("0");
                                  sb.Append(s).Append("Z");
                                  var text = sb.ToString();
                                  return text;
                                  }

                                  [Benchmark]
                                  public string CustomDev2WithMS()
                                  {
                                  var u = dateTime.ToUniversalTime();
                                  var sb = new StringBuilder(23);
                                  var y = u.Year;
                                  var d = u.Day;
                                  var M = u.Month;
                                  var h = u.Hour;
                                  var m = u.Minute;
                                  var s = u.Second;
                                  var ms = u.Millisecond;
                                  sb.Append(y).Append("-");
                                  if (M <= 9)
                                  sb.Append("0");
                                  sb.Append(M).Append("-");
                                  if (d <= 9)
                                  sb.Append("0");
                                  sb.Append(d).Append("T");
                                  if (h <= 9)
                                  sb.Append("0");
                                  sb.Append(h).Append(":");
                                  if (m <= 9)
                                  sb.Append("0");
                                  sb.Append(m).Append(":");
                                  if (s <= 9)
                                  sb.Append("0");
                                  sb.Append(s).Append(".");
                                  sb.Append(ms).Append("Z");
                                  var text = sb.ToString();
                                  return text;
                                  }
                                  [Benchmark]
                                  public string FormatO()
                                  {
                                  var text = dateTime.ToUniversalTime().ToString("o");
                                  return text;
                                  }
                                  [Benchmark]
                                  public string FormatS()
                                  {
                                  var text = string.Concat(dateTime.ToUniversalTime().ToString("s"),"Z");
                                  return text;
                                  }

                                  [Benchmark]
                                  public string FormatS_Verify()
                                  {
                                  var text = string.Concat(dateTime.ToUniversalTime().ToString("s"), "Z");
                                  return text;
                                  }

                                  [Benchmark]
                                  public string CustomFormatK()
                                  {
                                  var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                  return text;
                                  }

                                  [Benchmark]
                                  public string CustomFormatK_Verify()
                                  {
                                  var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                  return text;
                                  }
                                  }


                                  https://github.com/dotnet/BenchmarkDotNet was used






                                  share|improve this answer




























                                    5












                                    5








                                    5







                                    It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.



                                    Also it is interesting that "S" format is slow on Classic and fast on Core...



                                    Of course numbers are very close, between some rows difference is insignificant (tests with suffix _Verify are the same as those that are without that suffix, demonstrates results repeatability)



                                    BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
                                    Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
                                    Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
                                    [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                    Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                    Core : .NET Core 4.6.25009.03, 64bit RyuJIT


                                    Method | Job | Runtime | Mean | Error | StdDev | Median | Min | Max | Rank | Gen 0 | Allocated |
                                    --------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
                                    CustomDev1 | Clr | Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns | 8 | 0.1086 | 424 B |
                                    CustomDev2 | Clr | Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns | 7 | 0.1165 | 424 B |
                                    CustomDev2WithMS | Clr | Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns | 10 | 0.1625 | 592 B |
                                    FormatO | Clr | Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns | 14 | 0.2897 | 976 B |
                                    FormatS | Clr | Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns | 13 | 0.2865 | 984 B |
                                    FormatS_Verify | Clr | Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns | 12 | 0.2885 | 984 B |
                                    CustomFormatK | Clr | Clr | 912.2 ns | 17.915 ns | 18.398 ns | 916.6 ns | 878.3 ns | 934.1 ns | 4 | 0.0629 | 240 B |
                                    CustomFormatK_Verify | Clr | Clr | 894.0 ns | 3.877 ns | 3.626 ns | 893.8 ns | 885.1 ns | 900.0 ns | 3 | 0.0636 | 240 B |
                                    CustomDev1 | Core | Core | 989.1 ns | 12.550 ns | 11.739 ns | 983.8 ns | 976.8 ns | 1,015.5 ns | 6 | 0.1101 | 423 B |
                                    CustomDev2 | Core | Core | 964.3 ns | 18.826 ns | 23.809 ns | 954.1 ns | 935.5 ns | 1,015.6 ns | 5 | 0.1267 | 423 B |
                                    CustomDev2WithMS | Core | Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns | 9 | 0.1752 | 590 B |
                                    FormatO | Core | Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns | 11 | 0.0656 | 271 B |
                                    FormatS | Core | Core | 993.5 ns | 19.272 ns | 24.372 ns | 999.4 ns | 954.2 ns | 1,029.5 ns | 6 | 0.0633 | 279 B |
                                    FormatS_Verify | Core | Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns | 976.1 ns | 1,024.3 ns | 6 | 0.0674 | 279 B |
                                    CustomFormatK | Core | Core | 878.2 ns | 17.017 ns | 20.898 ns | 877.7 ns | 851.4 ns | 928.1 ns | 2 | 0.0555 | 215 B |
                                    CustomFormatK_Verify | Core | Core | 863.6 ns | 3.968 ns | 3.712 ns | 863.0 ns | 858.6 ns | 870.8 ns | 1 | 0.0550 | 215 B |


                                    Code:



                                        public class BenchmarkDateTimeFormat
                                    {
                                    public static DateTime dateTime = DateTime.Now;

                                    [Benchmark]
                                    public string CustomDev1()
                                    {
                                    var d = dateTime.ToUniversalTime();
                                    var sb = new StringBuilder(20);

                                    sb.Append(d.Year).Append("-");
                                    if (d.Month <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Month).Append("-");
                                    if (d.Day <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Day).Append("T");
                                    if (d.Hour <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Hour).Append(":");
                                    if (d.Minute <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Minute).Append(":");
                                    if (d.Second <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Second).Append("Z");
                                    var text = sb.ToString();
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomDev2()
                                    {
                                    var u = dateTime.ToUniversalTime();
                                    var sb = new StringBuilder(20);
                                    var y = u.Year;
                                    var d = u.Day;
                                    var M = u.Month;
                                    var h = u.Hour;
                                    var m = u.Minute;
                                    var s = u.Second;
                                    sb.Append(y).Append("-");
                                    if (M <= 9)
                                    sb.Append("0");
                                    sb.Append(M).Append("-");
                                    if (d <= 9)
                                    sb.Append("0");
                                    sb.Append(d).Append("T");
                                    if (h <= 9)
                                    sb.Append("0");
                                    sb.Append(h).Append(":");
                                    if (m <= 9)
                                    sb.Append("0");
                                    sb.Append(m).Append(":");
                                    if (s <= 9)
                                    sb.Append("0");
                                    sb.Append(s).Append("Z");
                                    var text = sb.ToString();
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomDev2WithMS()
                                    {
                                    var u = dateTime.ToUniversalTime();
                                    var sb = new StringBuilder(23);
                                    var y = u.Year;
                                    var d = u.Day;
                                    var M = u.Month;
                                    var h = u.Hour;
                                    var m = u.Minute;
                                    var s = u.Second;
                                    var ms = u.Millisecond;
                                    sb.Append(y).Append("-");
                                    if (M <= 9)
                                    sb.Append("0");
                                    sb.Append(M).Append("-");
                                    if (d <= 9)
                                    sb.Append("0");
                                    sb.Append(d).Append("T");
                                    if (h <= 9)
                                    sb.Append("0");
                                    sb.Append(h).Append(":");
                                    if (m <= 9)
                                    sb.Append("0");
                                    sb.Append(m).Append(":");
                                    if (s <= 9)
                                    sb.Append("0");
                                    sb.Append(s).Append(".");
                                    sb.Append(ms).Append("Z");
                                    var text = sb.ToString();
                                    return text;
                                    }
                                    [Benchmark]
                                    public string FormatO()
                                    {
                                    var text = dateTime.ToUniversalTime().ToString("o");
                                    return text;
                                    }
                                    [Benchmark]
                                    public string FormatS()
                                    {
                                    var text = string.Concat(dateTime.ToUniversalTime().ToString("s"),"Z");
                                    return text;
                                    }

                                    [Benchmark]
                                    public string FormatS_Verify()
                                    {
                                    var text = string.Concat(dateTime.ToUniversalTime().ToString("s"), "Z");
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomFormatK()
                                    {
                                    var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomFormatK_Verify()
                                    {
                                    var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                    return text;
                                    }
                                    }


                                    https://github.com/dotnet/BenchmarkDotNet was used






                                    share|improve this answer















                                    It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.



                                    Also it is interesting that "S" format is slow on Classic and fast on Core...



                                    Of course numbers are very close, between some rows difference is insignificant (tests with suffix _Verify are the same as those that are without that suffix, demonstrates results repeatability)



                                    BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
                                    Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
                                    Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
                                    [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                    Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
                                    Core : .NET Core 4.6.25009.03, 64bit RyuJIT


                                    Method | Job | Runtime | Mean | Error | StdDev | Median | Min | Max | Rank | Gen 0 | Allocated |
                                    --------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
                                    CustomDev1 | Clr | Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns | 8 | 0.1086 | 424 B |
                                    CustomDev2 | Clr | Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns | 7 | 0.1165 | 424 B |
                                    CustomDev2WithMS | Clr | Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns | 10 | 0.1625 | 592 B |
                                    FormatO | Clr | Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns | 14 | 0.2897 | 976 B |
                                    FormatS | Clr | Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns | 13 | 0.2865 | 984 B |
                                    FormatS_Verify | Clr | Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns | 12 | 0.2885 | 984 B |
                                    CustomFormatK | Clr | Clr | 912.2 ns | 17.915 ns | 18.398 ns | 916.6 ns | 878.3 ns | 934.1 ns | 4 | 0.0629 | 240 B |
                                    CustomFormatK_Verify | Clr | Clr | 894.0 ns | 3.877 ns | 3.626 ns | 893.8 ns | 885.1 ns | 900.0 ns | 3 | 0.0636 | 240 B |
                                    CustomDev1 | Core | Core | 989.1 ns | 12.550 ns | 11.739 ns | 983.8 ns | 976.8 ns | 1,015.5 ns | 6 | 0.1101 | 423 B |
                                    CustomDev2 | Core | Core | 964.3 ns | 18.826 ns | 23.809 ns | 954.1 ns | 935.5 ns | 1,015.6 ns | 5 | 0.1267 | 423 B |
                                    CustomDev2WithMS | Core | Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns | 9 | 0.1752 | 590 B |
                                    FormatO | Core | Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns | 11 | 0.0656 | 271 B |
                                    FormatS | Core | Core | 993.5 ns | 19.272 ns | 24.372 ns | 999.4 ns | 954.2 ns | 1,029.5 ns | 6 | 0.0633 | 279 B |
                                    FormatS_Verify | Core | Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns | 976.1 ns | 1,024.3 ns | 6 | 0.0674 | 279 B |
                                    CustomFormatK | Core | Core | 878.2 ns | 17.017 ns | 20.898 ns | 877.7 ns | 851.4 ns | 928.1 ns | 2 | 0.0555 | 215 B |
                                    CustomFormatK_Verify | Core | Core | 863.6 ns | 3.968 ns | 3.712 ns | 863.0 ns | 858.6 ns | 870.8 ns | 1 | 0.0550 | 215 B |


                                    Code:



                                        public class BenchmarkDateTimeFormat
                                    {
                                    public static DateTime dateTime = DateTime.Now;

                                    [Benchmark]
                                    public string CustomDev1()
                                    {
                                    var d = dateTime.ToUniversalTime();
                                    var sb = new StringBuilder(20);

                                    sb.Append(d.Year).Append("-");
                                    if (d.Month <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Month).Append("-");
                                    if (d.Day <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Day).Append("T");
                                    if (d.Hour <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Hour).Append(":");
                                    if (d.Minute <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Minute).Append(":");
                                    if (d.Second <= 9)
                                    sb.Append("0");
                                    sb.Append(d.Second).Append("Z");
                                    var text = sb.ToString();
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomDev2()
                                    {
                                    var u = dateTime.ToUniversalTime();
                                    var sb = new StringBuilder(20);
                                    var y = u.Year;
                                    var d = u.Day;
                                    var M = u.Month;
                                    var h = u.Hour;
                                    var m = u.Minute;
                                    var s = u.Second;
                                    sb.Append(y).Append("-");
                                    if (M <= 9)
                                    sb.Append("0");
                                    sb.Append(M).Append("-");
                                    if (d <= 9)
                                    sb.Append("0");
                                    sb.Append(d).Append("T");
                                    if (h <= 9)
                                    sb.Append("0");
                                    sb.Append(h).Append(":");
                                    if (m <= 9)
                                    sb.Append("0");
                                    sb.Append(m).Append(":");
                                    if (s <= 9)
                                    sb.Append("0");
                                    sb.Append(s).Append("Z");
                                    var text = sb.ToString();
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomDev2WithMS()
                                    {
                                    var u = dateTime.ToUniversalTime();
                                    var sb = new StringBuilder(23);
                                    var y = u.Year;
                                    var d = u.Day;
                                    var M = u.Month;
                                    var h = u.Hour;
                                    var m = u.Minute;
                                    var s = u.Second;
                                    var ms = u.Millisecond;
                                    sb.Append(y).Append("-");
                                    if (M <= 9)
                                    sb.Append("0");
                                    sb.Append(M).Append("-");
                                    if (d <= 9)
                                    sb.Append("0");
                                    sb.Append(d).Append("T");
                                    if (h <= 9)
                                    sb.Append("0");
                                    sb.Append(h).Append(":");
                                    if (m <= 9)
                                    sb.Append("0");
                                    sb.Append(m).Append(":");
                                    if (s <= 9)
                                    sb.Append("0");
                                    sb.Append(s).Append(".");
                                    sb.Append(ms).Append("Z");
                                    var text = sb.ToString();
                                    return text;
                                    }
                                    [Benchmark]
                                    public string FormatO()
                                    {
                                    var text = dateTime.ToUniversalTime().ToString("o");
                                    return text;
                                    }
                                    [Benchmark]
                                    public string FormatS()
                                    {
                                    var text = string.Concat(dateTime.ToUniversalTime().ToString("s"),"Z");
                                    return text;
                                    }

                                    [Benchmark]
                                    public string FormatS_Verify()
                                    {
                                    var text = string.Concat(dateTime.ToUniversalTime().ToString("s"), "Z");
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomFormatK()
                                    {
                                    var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                    return text;
                                    }

                                    [Benchmark]
                                    public string CustomFormatK_Verify()
                                    {
                                    var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
                                    return text;
                                    }
                                    }


                                    https://github.com/dotnet/BenchmarkDotNet was used







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 30 '17 at 20:24

























                                    answered May 4 '17 at 22:21









                                    Roman PokrovskijRoman Pokrovskij

                                    4,454135184




                                    4,454135184























                                        1














                                        If you're developing under SharePoint 2010 or higher you can use



                                        using Microsoft.SharePoint;
                                        using Microsoft.SharePoint.Utilities;
                                        ...
                                        string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)





                                        share|improve this answer





















                                        • 18





                                          SharePoint, when your .Net isn't Java enough.

                                          – Henrik
                                          Feb 27 '15 at 15:30






                                        • 16





                                          Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                                          – nathanchere
                                          Jun 29 '15 at 8:27











                                        • Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                                          – binki
                                          Feb 15 '18 at 17:34
















                                        1














                                        If you're developing under SharePoint 2010 or higher you can use



                                        using Microsoft.SharePoint;
                                        using Microsoft.SharePoint.Utilities;
                                        ...
                                        string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)





                                        share|improve this answer





















                                        • 18





                                          SharePoint, when your .Net isn't Java enough.

                                          – Henrik
                                          Feb 27 '15 at 15:30






                                        • 16





                                          Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                                          – nathanchere
                                          Jun 29 '15 at 8:27











                                        • Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                                          – binki
                                          Feb 15 '18 at 17:34














                                        1












                                        1








                                        1







                                        If you're developing under SharePoint 2010 or higher you can use



                                        using Microsoft.SharePoint;
                                        using Microsoft.SharePoint.Utilities;
                                        ...
                                        string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)





                                        share|improve this answer















                                        If you're developing under SharePoint 2010 or higher you can use



                                        using Microsoft.SharePoint;
                                        using Microsoft.SharePoint.Utilities;
                                        ...
                                        string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jun 13 '16 at 11:03









                                        Peter Mortensen

                                        13.8k1987113




                                        13.8k1987113










                                        answered Mar 27 '13 at 10:17









                                        Simon LogicSimon Logic

                                        9415




                                        9415








                                        • 18





                                          SharePoint, when your .Net isn't Java enough.

                                          – Henrik
                                          Feb 27 '15 at 15:30






                                        • 16





                                          Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                                          – nathanchere
                                          Jun 29 '15 at 8:27











                                        • Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                                          – binki
                                          Feb 15 '18 at 17:34














                                        • 18





                                          SharePoint, when your .Net isn't Java enough.

                                          – Henrik
                                          Feb 27 '15 at 15:30






                                        • 16





                                          Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                                          – nathanchere
                                          Jun 29 '15 at 8:27











                                        • Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                                          – binki
                                          Feb 15 '18 at 17:34








                                        18




                                        18





                                        SharePoint, when your .Net isn't Java enough.

                                        – Henrik
                                        Feb 27 '15 at 15:30





                                        SharePoint, when your .Net isn't Java enough.

                                        – Henrik
                                        Feb 27 '15 at 15:30




                                        16




                                        16





                                        Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                                        – nathanchere
                                        Jun 29 '15 at 8:27





                                        Using SharePoint for this is kind of like bringing a tub of jelly, a wet box of matches and 2 trapeze-walking chimpanzees to a gun fight.

                                        – nathanchere
                                        Jun 29 '15 at 8:27













                                        Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                                        – binki
                                        Feb 15 '18 at 17:34





                                        Even in SharePoint hopefully you can use the BCL’s .ToString("o") or, better, $"My complicated string {dt:o}".

                                        – binki
                                        Feb 15 '18 at 17:34











                                        1














                                        To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:



                                        public static string FormatDateTime(DateTime dateTime)
                                        {
                                        return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                                        }





                                        share|improve this answer
























                                        • I think this ISO date string is culture invariant per definition.

                                          – Jonas
                                          Feb 25 at 12:28
















                                        1














                                        To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:



                                        public static string FormatDateTime(DateTime dateTime)
                                        {
                                        return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                                        }





                                        share|improve this answer
























                                        • I think this ISO date string is culture invariant per definition.

                                          – Jonas
                                          Feb 25 at 12:28














                                        1












                                        1








                                        1







                                        To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:



                                        public static string FormatDateTime(DateTime dateTime)
                                        {
                                        return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                                        }





                                        share|improve this answer













                                        To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:



                                        public static string FormatDateTime(DateTime dateTime)
                                        {
                                        return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jun 22 '18 at 13:22









                                        nfgallimorenfgallimore

                                        340214




                                        340214













                                        • I think this ISO date string is culture invariant per definition.

                                          – Jonas
                                          Feb 25 at 12:28



















                                        • I think this ISO date string is culture invariant per definition.

                                          – Jonas
                                          Feb 25 at 12:28

















                                        I think this ISO date string is culture invariant per definition.

                                        – Jonas
                                        Feb 25 at 12:28





                                        I think this ISO date string is culture invariant per definition.

                                        – Jonas
                                        Feb 25 at 12:28


















                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f114983%2fgiven-a-datetime-object-how-do-i-get-an-iso-8601-date-in-string-format%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Costa Masnaga

                                        Fotorealismo

                                        Create new schema in PostgreSQL using DBeaver