0

I have one string ,it's look like a date format is 01/04/2013

For string date="01/04/2013"

The above string format lik a : 01 is Date , 04 is Month , and 2013 year .

Now i am using convert.todatetime()

See below :

DateTime **DateTimeValue** =Convert.ToDateTime(date);

The DateTimeValue return in my system : 01-04-2013T00:00:00 // Date 1st and month 2nd

But when converting the same DateTimeValue is return on other system :04-01-2013T00:00:00 //Month 1st and date 2nd

Why The Convert.DateTime() is return different ,different date in different system ????

Answer :

Now I changed my DataBase Coloumn DataType DateTime to Nvarchar . So I Shouldn't want convert To DateTime . and this is working in all system .

Thanks guy's

4 Answers4

4

Why The Convert.DateTime() is return different ,different date in different system ????

Because it uses the current culture to convert the string to datetime. In some culture the month comes before the date and in others vice-versa.

You can specify the culture or use CultureInfo.InvariantCulture(which is similar to en-US) or you can use DateTime.ParseExact where you can specify the format.

string date="01/04/2013";
 // day 4 month 1
DateTime dt = DateTime.Parse(date, CultureInfo.InvariantCulture); 

or

// day 4 month 1
DateTime dt = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture); 

In general it is a good idea to use the TryParse methods to detect if the input is in the correct format.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

It's a regional/localisation settings thing. The way to ensure this doesn't happen without knowing about these settings is to setup the date string like this: yyyy-mm-dd, e.g. 2013-04-01 which will always be seen as the 1st April 2013.

More info about Convert.ToDateTime here: http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx

The pertinent bit:

If value is not null, the return value is the result of invoking the DateTime.Parse method on value using the formatting information in a DateTimeFormatInfo object that is initialized for the current culture.

Tom Chantler
  • 14,753
  • 4
  • 48
  • 53
0

If you go on the control panel on your PC, there will be an option for Region and Language (this may vary in name depending on your version of Windows). From you here you can specify the format of long and short dates and times.

If you want the format to be exactly the same, use the ToString() method on the datetime with a format set, described here.

GrandMasterFlush
  • 6,269
  • 19
  • 81
  • 104
0

you can try this :

string date = "01/04/2013";
        DateTime dtTime;
        if (DateTime.TryParseExact(date, "dd/MM/yyyy",
           System.Globalization.CultureInfo.InvariantCulture,
           System.Globalization.DateTimeStyles.None, out dtTime))
        {
            Console.WriteLine(dtTime);
        }
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61