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
CodePudding user response:
It's because you used upper-case HH
instead of lower-case hh
in the format string. You also need the AM/PM indicator:
hh:mm tt
This is well-documented:
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:
<h4>Enter Date</h4> <asp:TextBox ID="txtDate" runat="server" TextMode="Date"> </asp:TextBox> <h4>Enter Time</h4> <asp:TextBox ID="txtTime" runat="server" TextMode="Time"> </asp:TextBox>
And code to load:
DateTime dtStart = DateTime.Now; txtDate.Text = dtStart.ToString(@"yyyy-MM-dd"); txtTime.Text = dtStart.ToString(@"HH:mm");
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: