Reputation: 61875
Is there a "short[er]" format specifier for an ISO-8601 representation without the [optional] fractional seconds?
That is, given
var n = DateTimeOffset.Now;
// short "s" format - 2014-02-14T10:41:49
n.ToString("s")
// short "o" format - 2014-02-14T10:41:49.7200222-08:00
n.ToString("o")
// desired output
// custom format - 2014-02-14T10:41:49-08:30
n.ToString("yyyy-MM-ddTHH:mm:sszzz")
is there a "short[er]" format specifier for the last case?
Context clarification: I'm using the formats primarily with string.Format
, where the long format can quickly muddle a format string.
Upvotes: 2
Views: 3683
Reputation: 3477
Sorry, misunderstood the question the first time around. IMHO an extension method would work the best:
class Program {
static void Main() {
Console.WriteLine(DateTimeOffset.Now.ToCustomString());
}
}
static class DateHelper {
public static string ToCustomString(this DateTimeOffset time) {
return time.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);
}
}
you need to specify CultureInfo.InvariantCulture
otherwise CurrentCulture
will be used which will substitute :
for the user's current regional time component separator which may not be a colon, and that would result in a non ISO 8601-compliant string.
If you need to use it in longer strings with multiple substitution fields maybe look into custom format providers.
Upvotes: 1