我想将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。
我将输出作为
23-12-2013
我应该如何获得输出?
23/12/2013
考虑另一种情况, 假设,我有一个Customculture Info,我想转换我的日期w.r.t我的自定义文化, 我之前做的是如下,
string.Format(customCulture, "{0:G}", result);
现在如何使用customCulture在字符串中获取日期时间,它不应该依赖于系统DateTime?
答案 0 :(得分:13)
您的文化日期分隔符看起来像-
,而Tim pointed,/
会替换为它。
您应该使用CultureInfo.InvariantCulture
作为result.ToString()
方法中的第二个参数。
获取独立于文化(不变)的CultureInfo对象。
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。
答案 1 :(得分:3)
试试这个
Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
答案 2 :(得分:1)
您需要添加此
Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
现在您的代码变为
object value = new DateTime(2003, 12, 23, 6, 22, 30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
Console.ReadLine();
注意强> * 使用System.Globalization添加; *
答案 3 :(得分:0)
您可以使用不变文化:
Console.WriteLine(
result.ToString("dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture
);
答案 4 :(得分:0)
尝试
string.Format("{0:dd/MM/yyyy}",result)
祝你好运
永
答案 5 :(得分:0)
我完全同意Tim Schmelter的评论和SonerGönül的回答。只是想添加一下,当你使用日期时间格式时,你应该指定文化,因为默认文化将来自Thread.CurrentThread.CurrentCulture
(Control Panel->Region and Languages->Format
中设置的文化),这意味着使用不同的设置你的输入将是不同。
看看你的不同文化的例子:
object value = new DateTime(2003, 12, 23, 6, 22, 30);
DateTime result = (DateTime)value;
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
Console.WriteLine(result.ToString("dd/MM/yyyy", culture));
}
答案 6 :(得分:0)
'/'是一个特殊字符,表示“区域设置日期分隔符”。如果你想像普通的char一样使用它,你可以使用引号图'\'来引用它 例如:
DateTime.Now.ToString(@"dd\/MM\/yyyy")