Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Date Format to ddth mmm,yyyy

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");
like image 583
Alina Anjum Avatar asked Jan 07 '23 01:01

Alina Anjum


2 Answers

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.

like image 88
Mango Wong Avatar answered Jan 08 '23 14:01

Mango Wong


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);
like image 32
Rik Avatar answered Jan 08 '23 15:01

Rik