I am printing some dates on my webform.
Currently my Date Format is dd:mmm:yyyy hh:mm
How can I change the date format to ddth mmm,yyyy for
example 17th May,2016 hh:mm
Here is my Code :
lastlogin = DateTime.Parse(dt_LastLoginDetail.Rows[0]["login_time"].ToString());
lastlogindate = "Last Login Date: " + lastlogin.ToString("dd-MMM-yyy hh:mm tt");
Try this:
lastlogin = DateTime.Parse(dt_LastLoginDetail.Rows[0]["login_time"].ToString());
string suffix;
switch (lastlogin.Day) {
case 1:
case 21:
case 31:
suffix = "st";
break;
case 2:
case 22:
suffix = "nd";
break;
case 3:
case 23:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
lastlogindate = "Last Login Date: " + lastlogin.ToString("dd\"" + suffix + "\" MMM, yyyy hh:mm");
.Net does not have built-in method to retrieve 'st', 'nd', etc. So you simply need to determine in the code.
There is no standard Date format that generates the "st", "nd", "rd" or "th" suffix for you, as far as I'm aware. You could use the following:
DateTime dt = DateTime.Now;
string suffix = "th";
if (dt.Day < 10 || dt.Day > 20)
{
switch (dt.Day % 10)
{
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
}
string format = $"dd\"{suffix}\" MMM yyyy hh:mm";
string s = dt.ToString(format);
Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string; for more information:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
For showing 17th May 2016
DateTime.Now.ToString("dd'th ' MMM,yyyy");