Change date format in asp.net

RelatedRhymes

I have a table which stores dates of an event.I display the dates in a few labels.Everything works fine.BUT i want to display my dates in the format 'dd-mm-yyyy' and the date is stored in sql server as 'mm/dd/yyyy'.

 Create table testDate
 (
 EventStart date
 EventEnd date
 )

The dates come from datepicker and i dont want to format my dates in datepicker because it gives me conversion problems. I want to change the format when i display the date in asp.net Label. Right now i dsiplay the date as below :

 string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from testdate", con);
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            DateTime Received;
            DateTime.TryParse(rdr["EventStart"].ToString(),CultureInfo.InvariantCulture,DateTimeStyles.None, out Received);
            Label1.Text = Received.ToShortDateString();
        }
    }
}

Thanks in advance.

Soner Gönül

You don't need to parse it anyway. SQL Server saves DateTime in a binary format. It doesn't have any format. Format concept only an issue when you get their textual representation.

Just cast it to DateTime (which is date mapped with DateTime in CLR side) and use custom date and time format specifiers to get it's string representation with which format you want.

Label1.Text = ((DateTime)rdr["EventStart"]).ToString("dd-MM-yyyy");

By the way, I strongly suspect you need to use month instead of minutes. That's why you need to change your mm part to MM. mm specifier is for minutes and MM specifier is for months.

Use using statement to dispose your SqlCommand and SqlDataReader objects like you did your connection.

Do not use select * by the way. It is kind of bad practice.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive