在 C# 中将 dateTime 转换为 ISO 格式 yyyy-mm-dd hh:mm:ss
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1912894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#
提问by Chin
采纳答案by Guffa
There is no standard format for the readable 8601 format. You can use a custom format:
可读的 8601 格式没有标准格式。您可以使用自定义格式:
theDate.ToString("yyyy-MM-dd HH':'mm':'ss")
(The standard format "s" will give you a "T" between the date and the time, not a space.)
(标准格式“s”会在日期和时间之间给你一个“T”,而不是空格。)
回答by CMS
To use the strict ISO8601
, you can use the s
(Sortable) format string:
要使用 strict ISO8601
,您可以使用s
(Sortable)格式字符串:
myDate.ToString("s"); // example 2009-06-15T13:45:30
It's a short-hand to this custom format string:
这是这个自定义格式字符串的简写:
myDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
And of course, you can build your own custom format strings.
当然,您可以构建自己的自定义格式字符串。
More info:
更多信息:
回答by A9S6
The DateTime::ToString() method has a string formatter that can be used to output datetime in any required format. See DateTime.ToString Method (String)for more information.
DateTime::ToString() 方法有一个字符串格式化程序,可用于以任何所需格式输出日期时间。有关详细信息,请参阅DateTime.ToString 方法(字符串)。
回答by codea
For those who are using this format all the timme like me I did an extension method. I just wanted to share because I think it can be usefull to you.
对于那些像我一样一直使用这种格式的人,我做了一个扩展方法。我只是想分享,因为我认为它对你有用。
/// <summary>
/// Convert a date to a human readable ISO datetime format. ie. 2012-12-12 23:01:12
/// this method must be put in a static class. This will appear as an available function
/// on every datetime objects if your static class namespace is declared.
/// </summary>
public static string ToIsoReadable(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd HH':'mm':'ss");
}
回答by Luis
date.ToString("o") // The Round-trip ("O", "o") Format Specifier
date.ToString("s") // The Sortable ("s") Format Specifier, conforming to ISO86801
回答by Mick P
To add a little bit more information that confused me; I had always thought the same result could be achieved like so;
添加更多让我感到困惑的信息;我一直认为这样可以达到同样的结果;
theDate.ToString("yyyy-MM-dd HH:mm:ss")
However, If your Current Culture doesn't use a colon(:) as the hour separator, and instead uses a full-stop(.) it could return as follow:
但是,如果您的当前文化不使用冒号 (:) 作为小时分隔符,而是使用句号 (.),它可能会返回如下:
2009-06-15 13.45.30
2009-06-15 13.45.30
Just wanted to add why the answer provided needs to be as it is;
只是想补充一下为什么提供的答案需要保持原样;
theDate.ToString("yyyy-MM-dd HH':'mm':'ss")
:-)
:-)