Change Date Format to ddth mmm,yyyy

梦想的初衷 提交于 2019-12-10 17:18:58

问题


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");

回答1:


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.




回答2:


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);



回答3:


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");


来源:https://stackoverflow.com/questions/37272514/change-date-format-to-ddth-mmm-yyyy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!