user2431727 user2431727 - 5 months ago 22
SQL Question

How to extract date and month part from datetime field in database

I have a datetime column named "submitted_date". One of it's value in database is 5/12/2017 11:09:50 AM. Now I want to extract only date and month part of it. How to display it in a format like "May-12".
My code is here,

using (SqlConnection con = obj.getcon())
{
con.Open();
string query = "SELECT submitted_date FROM sample";
using (SqlCommand command = new SqlCommand(query, con))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string x_val = reader[0].ToString(); // 5/12/2017 11:09:50 AM
}
}
}
con.Close();
}

Answer Source

To get the alphabetic month name you can use MMM. Here is the code:

var result = DateTime.Parse(reader[0].ToString())  
                     .ToString("MMMM-dd", CultureInfo.InvariantCulture);
//if reader[0].ToString(): 5/12/2017 11:09:50 AM then
//result: May-12