-3

There's a ton of articles on this but I can't find exactly what I am looking for. I want to match what Java does so I think I need:

DateTime Kind=unknown => 2020-07-08T02:03:04
DateTime Kind=UTC => 2020-07-08T02:03:04Z
DateTime Kind=local => 2020-07-08T02:03:04-08:00
DateTimeOffset UTC => 2020-07-08T02:03:04Z
DateTimeOffset Denver => 2020-07-08T02:03:04-08:00
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • 3
    This isn’t clear at all. Can you provide sample inputs and the output you want? – stuartd Jul 08 '20 at 22:41
  • 1
    Huh? Which part(s) of which line(s) are you trying to create? `yyyy-MM-dd\Thh:mm:ss` with an optional offset? – Lance U. Matthews Jul 08 '20 at 22:42
  • Please provide a [mcve] so we at least have the input values to work with. – mjwills Jul 08 '20 at 23:04
  • I was writing an answer when it was closed: You want either `dateTime.ToString("u").Replace(' ', 'T')` or `dateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssK")`, and then `dateTimeOffset.ToString(dateTimeOffset.Offset == TimeSpan.Zero ? : "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" : "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz")` – madreflection Jul 08 '20 at 23:08
  • 1
    It sounds like you're looking for [the `"o"` specifier](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#the-round-trip-o-o-format-specifier). It will match everything you asked, except in a `DateTimeOffset` it will produce `+00:00` instead of `Z` because there's nothing in a `DateTimeOffset` that makes it explicitly UTC. ALSO - you might be interested in [the `"K"` specifier](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#KSpecifier) for `DateTime` types - to be used in a custom format string. – Matt Johnson-Pint Jul 13 '20 at 17:48

1 Answers1

1

You've listed multiple DateTime formats. Which one do you want?

See (standard formats):

https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

and (custom formats):

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

For the authoritative docs.

For your first example, you would probably want 'Sortable date time pattern': myDateTime.ToString("s")

Jonathan
  • 4,916
  • 2
  • 20
  • 37
  • I'm trying to match the standard Java toString() for each of LocalDateTime, ZonedDateTime, and OffsetDateTime. I believe these match the ISO standard for displaying each. – David Thielen Jul 08 '20 at 22:59