我无法将文本(Maskedtextbox
(转换为Datetime
。 例如,我在面具中有这些时间:16:30
,6:30
我想在第三张蒙面10:00
中展示 这是我的代码:我写一个方法
我有一行错误:时间跨度t 错误是:输入字符串格式不正确
公共无效 A(屏蔽文本框 k、屏蔽文本框 k1、屏蔽文本框 k2、标签 k3( { string[] houre = k.Text.Split(':'(; 尝试 { int h = int。Parse (houre[0].ToString((; int m = int。Parse (houre[1]。ToString((;
if (h > 23)
{
MessageBox.Show("wrong hour");
k.Text = "00:" + houre[1].ToString();
}
if (m > 59)
{
MessageBox.Show("wrong minute");
k.Text = houre[0].ToString() + ":00";
}
if (h > 23 && m > 59)
k.Text = "00:00";
}
catch (Exception)
{
}
string[] houre1 = k1.Text.Split(':');
try
{
int h1 = int.Parse(houre1[0].ToString());
int m1 = int.Parse(houre1[1].ToString());
if (h1 > 23)
{
MessageBox.Show("wrong hour");
k1.Text = "00:" + houre1[1].ToString();
}
if (m1 > 59)
{
MessageBox.Show("wrong minute");
k1.Text = houre1[0].ToString() + ":00";
}
if (h1 > 23 && m1 > 59)
k1.Text = "00:00";
}
catch (Exception)
{
}
TimeSpan t = TimeSpan.ParseExact(k.Text.Trim(':'), "hh:mm",null );
TimeSpan t1 = TimeSpan.ParseExact(k1.Text, "hh:mm", CultureInfo.InvariantCulture);
k2.Text = (t1 - t).ToString("hh:mm", CultureInfo.InvariantCulture);
if (k.Text != "" && k1.Text != "")
k3.Text = "IN OUT Complete";
else
k3.Text = "IN OUT Noncomplete";
你实际上使用TimeSpan
(不是DateTime
(;你应该Parse
,做算术,最后,将结果格式化为String
:
TimeSpan left = TimeSpan.ParseExact(
maskedBox1.Text.Trim(), "h\:m", CultureInfo.InvariantCulture);
TimeSpan right = TimeSpan.ParseExact(
maskedBox2.Text.Trim(), "h\:m", CultureInfo.InvariantCulture);
myMaskedBox.Text = (left - right).ToString("hh\:mm", CultureInfo.InvariantCulture);
您可以尝试以下代码:
'''
var timeString1 = "16:30";
var timeString2 = "6:30";
//Make sure the parse input string match the HH:mm format
timeString1 = timeString1.PadLeft(5, '0');
timeString2 = timeString2.PadLeft(5, '0');
var time1 = DateTime.ParseExact(timeString1, "HH:mm", null);
var time2 = DateTime.ParseExact(timeString2, "HH:mm", null);
var timeSpan12 = time1 - time2;
var result = $"{timeSpan12.Hours:d2}:{timeSpan12.Minutes:d2}";
Console.WriteLine(result);//10:30
'''
我找到好方法:
公共静态长时间(字符串 t( { 返回 (长。Parse(t.Substring(0,2(( * TimeSpan.TicksPerHour(+ (长。Parse(t.Substring(3,2((*TimeSpan.TicksPerMinute(;
}
公共无效计算(屏蔽文本框 a,屏蔽文本框b,屏蔽文本框 c( {
if (Time(b.Text) > Time(a.Text))
{
long q;
q = (Time(b.Text) - Time(a.Text)) / TimeSpan.TicksPerMinute;
c.Text = TimeSpan.FromMinutes(q).ToString();
}
if (Time(b.Text) < Time(a.Text))
{
long q;
q = ((Time(b.Text)+24*TimeSpan.TicksPerHour) - Time(a.Text)) /
TimeSpan.TicksPerMinute;
c.Text = TimeSpan.FromMinutes(q).ToString();
}
if (Time(b.Text) == Time(a.Text))
c.Text = "00:00";
}