Click here to Skip to main content
15,910,886 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello I have got this SqlDataReader which reads date datatype from SQL DB into maskedTextBox with mask MM/DD/YYYY but when the date is e.g. 05/05/2005 it would be displayed in maskedtextbox like this 55/20/05__ on Windows XP .

Is there solution to prevent this?

On Windows 8 it is read as 5_/5_/2005 which is correct

C#
string query = "SELECT * FROM events WHERE name='" + selectedrow + "' AND year='" + selectedyear+ "'";
           SqlCommand command= new SqlCommand(query, con);
           con.Open();
           SqlDataReader read= command.ExecuteReader();


           if (read.Read())
           {


               object nulldate = (maskedTextBox2.Text = read.IsDBNull(24) ?
                   string.Empty : read.GetDateTime(24).ToShortDateString()); } con.Close
Posted

1 solution

In MSDN, it is stated that:

Quote:
The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.


I would recommend enforcing a predefined DateTime format in inserting data to DB and in retrieving it such as:

C#
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] dateValues = { "30-12-2011", "12-30-2011",
                              "30-12-11", "12-30-11" };
      string pattern = "MM-dd-yy";
      DateTime parsedDate;

      foreach (var dateValue in dateValues) {
         if (DateTime.TryParseExact(dateValue, pattern, null,
                                   DateTimeStyles.None, out parsedDate))
            Console.WriteLine("Converted '{0}' to {1:d}.",
                              dateValue, parsedDate);
         else
            Console.WriteLine("Unable to convert '{0}' to a date and time.",
                              dateValue);
      }
   }
}
// The example displays the following output:
//    Unable to convert '30-12-2011' to a date and time.
//    Unable to convert '12-30-2011' to a date and time.
//    Unable to convert '30-12-11' to a date and time.
//    Converted '12-30-11' to 12/30/2011.


You can find more info in MSDN: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900