如何将文本框值转换为时间?

发布于 2025-01-28 23:05:29 字数 397 浏览 2 评论 0原文

我想通过减去当前时间和文本框时间来将我的文本框值转换为时间,并计算所花费的时间。但是,在输入文本框的时间后,发生了一个例外。

这是我遇到错误的代码;

system.formatexception:'字符串未被识别为有效

DateTime timeValue = DateTime.ParseExact(txtTime.Text, "M/d/yyyy", CultureInfo.InvariantCulture);

DateTime timeValue = Convert.ToDateTime(txtTime.Text); 

也尝试过,但它不起作用。谁能帮我吗?

I want to convert my textbox value to the time and calculate the hours spent by subtracting current time and textbox time. But after entering the time for textbox, an exception occurred.

This is my code where I'm getting an error;

System.FormatException: 'String was not recognized as a valid

DateTime timeValue = DateTime.ParseExact(txtTime.Text, "M/d/yyyy", CultureInfo.InvariantCulture);

I tried

DateTime timeValue = Convert.ToDateTime(txtTime.Text); 

also but it didn't work. Can anyone help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉城凉梦凉人心 2025-02-04 23:05:29

您需要使用HH:MM而不是m/d/yyyy在解析用户输入时仅使用dateTime.tryparseexact获得时间。

private void GetTimeButton_Click(object sender, EventArgs e)
{
    string format = "Valid format is HH:mm";
    if (!string.IsNullOrWhiteSpace(TimeTextBox.Text))
    {
        TimeLabel.Text = DateTime.TryParseExact(TimeTextBox.Text, "HH:mm", 
            CultureInfo.InvariantCulture, DateTimeStyles.None, out var time) ?
            time.ToShortTimeString() : 
            format;
    }
    else
    {
        TimeLabel.Text = format;
    }
}

注释上面的时间为24小时,例如输入01:00是1:00 AM 13:00是1:00 pm

You need to use HH:mm rather than M/d/yyyy when parsing user input to obtain time only using DateTime.TryParseExact.

private void GetTimeButton_Click(object sender, EventArgs e)
{
    string format = "Valid format is HH:mm";
    if (!string.IsNullOrWhiteSpace(TimeTextBox.Text))
    {
        TimeLabel.Text = DateTime.TryParseExact(TimeTextBox.Text, "HH:mm", 
            CultureInfo.InvariantCulture, DateTimeStyles.None, out var time) ?
            time.ToShortTimeString() : 
            format;
    }
    else
    {
        TimeLabel.Text = format;
    }
}

Note the above is 24 hour time e.g. enter 01:00 is 1:00 AM while entering 13:00 is 1:00 PM

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文