简体   繁体   English

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

[英]c# converting datetime in a different culture

I'm trying to convert a german DateTime value into a french DateTime object. 我正在尝试将德语DateTime值转换为法语DateTime对象。

The value of my item called "_dateFacture" is "08.07.2015 17:23:01" 我的项目“_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"

How is it possible for the object testfinal to get a value like that ? 对象testfinal如何获得这样的值?

If you had declared the datatype with each variable, instead of using var, it would have been easier to spot. 如果您已经使用每个变量声明了数据类型,而不是使用var,那么它将更容易被发现。

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

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

testfinal is a DateTime, not a string. testfinal是DateTime,而不是字符串。

When you look at it in a debugger or view, testfinal is converted to a string using DateTime.ToString() which uses the current culture (which presumably displays dates with a dot). 当您在调试器或视图中查看它时,testfinal将使用DateTime.ToString()转换为字符串,该字符串使用当前文化(可能显示带点的日期)。

What you saw is just a representation issue. 你看到的只是一个代表问题。 They are the same DateTime values. 它们是相同的DateTime值。

DateTime doesn't have any implicit format. DateTime没有任何隐式格式。 And it doesn't have any IFormatProvider . 它没有任何 IFormatProvider It just a date and time values. 它只是一个日期和时间值。 Format is only a subject when you try to get it's textual representation. 当您尝试获取文本表示时,格式只是一个主题。

I strongly suspect you see this in your debugger or something; 我强烈怀疑你在调试器或其他东西中看到了这个;

在此输入图像描述

Your stringdate is a string , but your testfinal is a DateTime . 您的stringdate是一个string ,但您的testfinal是一个DateTime If you wanna save your datetime values in your database, don't save their string representations. 如果要在数据库中保存日期时间值,请不要保存其字符串表示形式。 Put your datetime values directly to your parameterized queries. 将您的日期时间值直接放入参数化查询中。

Read: Bad habits to kick : choosing the wrong data type 阅读: 糟糕的习惯:选择错误的数据类型

if you want to store testfinal as a datetime, you just need to make sure your var is in fact a DateTime. 如果你想将testfinal存储为日期时间,你只需要确保你的var实际上是一个DateTime。

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

To show it you can use a format in the ToString function: 要显示它,您可以使用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