SajuPK
SajuPK

Reputation: 97

How to make the time format from h:m tt to hh:mm tt in c#

I am trying to show time(s) in a dropdown. I managed to do so using this code:-

        DateTime dtTime = new DateTime(2015,01,01,00,00,00);

        DataTable dt = new DataTable();
        dt.Columns.Add("time");

        for (int i = 0; i < 48; i++)
        {
            string tm = dtTime.ToShortTimeString();
            DataRow dr = dt.NewRow();
            dr["time"] = tm;
            dt.Rows.Add(dr);

            dtTime = dtTime.AddMinutes(30);
        }

        ddlTime.DataSource = dt;
        ddlTime.DataTextField = "time";
        ddlTime.DataValueField = "time";
        ddlTime.DataBind();

The output is :-

enter image description here

Now, I want to make the format hh:mm tt. for example, 1:00 AM should be 01:00 AM. Can anyone help me? Thanks.

Upvotes: 0

Views: 675

Answers (3)

Jack
Jack

Reputation: 360

string tm = dtTime.ToString("hh:mm tt");

Upvotes: 1

fubo
fubo

Reputation: 45947

replace

dtTime.ToShortTimeString();

with

dtTime.ToString("hh:mm tt");

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

dtTime = dtTime.AddMinutes(30).ToString("HH:mm tt");

Upvotes: 1

Related Questions