I working on with C# and ASP.NET webforms using Visual Studio 2022. I have an issue when trying to write time to a textbox.
When I try to write time 11:30 pm
to a textbox, it is converted automatically to 23:30 – why was it converted?
I need time to working on 12 hours mode exactly as I write it.
So if I write 11:30 am
, it must be shown as 11:30 am
.
11:30 pm
must be shown as 11:30 pm
– here I have the issue that it is converted to 23:30 pm
.
Expected result:
- when I write
11:30 pm
, it must show11:30 pm
What do I do to solve this issue please?
webpage.cs
protected void txtFromTime_TextChanged(object sender, EventArgs e)
{
var Transactiondate = Convert.ToDateTime(txtDate.Text);
var dateonly = Transactiondate.ToString("dd/MM/yyyy");
var eventDate = txtDate.Text + " " +Convert.ToDateTime(txtFromTime.Text).ToString("HH:mm");
Label1.Text = eventDate.ToString();
}
web page.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDate" runat="server" Text="Date" ></asp:Label>
<asp:TextBox ID="txtDate" runat="server" TextMode="Date" AutoPostBack = "True" OnTextChanged="txtDate_TextChanged"></asp:TextBox>
<asp:Label ID="lblFromTime" runat="server" Text="FromTime"></asp:Label>
<asp:TextBox ID="txtFromTime" runat="server" TextMode="Time" AutoPostBack = "True" OnTextChanged="txtFromTime_TextChanged"></asp:TextBox>
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
picture issue
2
Answers
It’s because you used upper-case
HH
instead of lower-casehh
in the format string. You also need the AM/PM indicator:This is well-documented:
Unfortunately, right now this always results in an uppercase indicator, so you’ll see
11:30 PM
. If you really need to see11:30 pm
you need to correct it with normal string manipulation.I’d like to see the
t
("t"ime of day) specifiers enhanced, such that lowercaset
is a lowercase indicator and uppercaseT
is an uppercase indicator, along with a mechanism to infer the case from the system’s datetime format. I suspect the reason this has not happened is a certain important time format uses a literalT
to separate the date and time portions of the string.why not consider just one text box, and use textmode=
So, say this text box:
You then get/see this:
In other words, you have one text box – it will have both date and time for you.
About the only thing I don’t like, is tab key does not select, you have to hit enter key.
but, it also allows in-line editing if you don’t want to use the picker.
Hence this:
And if you enter (without the picker), then you have to use arrow keys to move to the next part. Again, I don’t find this 100% intuitive.
However, you can drop in 2 controls, and feed it the "one" date time variable. You feed using "iso" date format, but it will take on your local settings.
So, say this markup:
And code to load:
NOTE close above, I feed the time a 24 hour format, but it does display in 12 hour format.
and now we get/see this: