繁体   English   中英

c#在不同的文化中转换日期时间

[英]c# converting datetime in a different culture

我正在尝试将德语DateTime值转换为法语DateTime对象。

我的项目“_dateFacture”的值是“08.07.2015 17:23:01”

var stringdate = _dateFacture.ToString(new CultureInfo("fr-FR")); //d2 = "08/07/2015 17:23:01"
var testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR")); // testfinal = "08.07.2015 17:23:01"

对象testfinal如何获得这样的值?

如果您已经使用每个变量声明了数据类型,而不是使用var,那么它将更容易被发现。

  string stringdate = _dateFacture.ToString(new CultureInfo("fr-FR")); 

  DateTime testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR")); 

testfinal是DateTime,而不是字符串。

当您在调试器或视图中查看它时,testfinal将使用DateTime.ToString()转换为字符串,该字符串使用当前文化(可能显示带点的日期)。

你看到的只是一个代表问题。 它们是相同的DateTime值。

DateTime没有任何隐式格式。 它没有任何 IFormatProvider 它只是一个日期和时间值。 当您尝试获取文本表示时,格式只是一个主题。

我强烈怀疑你在调试器或其他东西中看到了这个;

在此输入图像描述

您的stringdate是一个string ,但您的testfinal是一个DateTime 如果要在数据库中保存日期时间值,请不要保存其字符串表示形式。 将您的日期时间值直接放入参数化查询中。

阅读: 糟糕的习惯:选择错误的数据类型

如果你想将testfinal存储为日期时间,你只需要确保你的var实际上是一个DateTime。

DateTime testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR")); 

要显示它,您可以使用ToString函数中的格式:

string formattedDate = testfinal.ToString("dd.MM.yyyy HH:mm:ss");
//now your formattedDate  will be "08.07.2015 17:23:01"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM