简体   繁体   中英

c# converting datetime in a different culture

I'm trying to convert a german DateTime value into a french DateTime object.

The value of my item called "_dateFacture" is "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 ?

If you had declared the datatype with each variable, instead of using var, it would have been easier to spot.

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

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

testfinal is a DateTime, not a string.

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).

What you saw is just a representation issue. They are the same DateTime values.

DateTime doesn't have any implicit format. And it doesn't have any 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 . 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.

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

To show it you can use a format in the ToString function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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