将DateTime转换为字符串 [英] Converting DateTime to string
问题描述
我想将 DateTime
转换为 String
。
检查以下代码。
namespace TestDateConvertion
{
class Program
{
static void Main(string[] args)
{
object value = new DateTime(2003,12,23,6,22,30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy"));
Console.ReadLine();
}
}
}
我已经更改了我的系统日期格式为Faeroese。
I have changed my system date format to Faeroese.
,我的输出为
23- 12-2013
23-12-2013
如何获取输出?
23/12/2013
23/12/2013
再考虑另一种情况,
假设我有一个自定义文化信息,我想转换我的日期wrt我的自定义文化,
我以前做的是如下,
And consider this another scenario, suppose, i have a Customculture Info , and i want to convert my date w.r.t my custom culture, what i was doing before was as follows,
string.Format(customCulture, "{0:G}", result);
现在我将如何使用customCulture获取字符串中的datetime,它不应该依赖于系统DateTime? / p>
now how shall i get the datetime in string using customCulture and it should not depend on system DateTime?
推荐答案
看起来你的文化日期分隔符是 -
和Tim 指向的, /
替换自己
Looks like your culture's date separator is -
and as Tim pointed, /
replaces itself with it.
您应该使用 CultureInfo.InvariantCulture
作为 result.ToString()
中的第二个参数方法。
You should use CultureInfo.InvariantCulture
as a second parameter in your result.ToString()
method.
获取文化独立(不变量)的CultureInfo对象。
Gets the CultureInfo object that is culture-independent (invariant).
object value = new DateTime(2003, 12, 23, 6, 22, 30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
输出将为;
23/12/2003
这里一个 DEMO 。
这篇关于将DateTime转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!