“String was not recognized as a valid TimeSpan. Error in C# inserting time to SQL database.”

huangapple go评论74阅读模式
英文:

String was not recognized as a valid TimeSpan. Error in C# inserting time to SQL database

问题

我正在使用这段代码将时间插入到SQL数据库中:

TimeSpan.Parse(string.Format(DateTime.Now.ToShortTimeString(), "hh:mm"));

我尝试更改时间的语法为"hh:mm:ss"和"hh:mm tt"。

英文:

I'm using this code to insert time into a SQL database:

TimeSpan.Parse(string.Format(DateTime.Now.ToShortTimeString(), "hh:Mi"))

I tried to change the syntax of time "hh:mm:ss" and "hh:mm tt"

答案1

得分: 2

以下是翻译好的部分:

你不应该使用任何字符串。如果你想要包含当前时间的 TimeSpan,那么创建它:

var currentTime = new TimeSpan(DateTime.Now.Hours, DateTime.Now.Minutes, 0);

如果你要保存到数据库列中,而该列是实际的时间数据类型,那就是你想要的。

正如评论中指出的那样,在上面的代码中,DateTime.Now 在两次使用之间有一个非零概率的小时变化。为了避免这种情况,你可以引入一个额外的变量,甚至重用相同的变量:

var currentTime = DateTime.Now;

currentTime = new TimeSpan(currentTime.Hours, currentTime.Minutes, 0);

我几乎错误地一开始写了 VB,并且打算使用 With 块来创建一个隐式变量,但是 C# 没有等价的功能。

英文:

You should not be using any strings at all. If you want a TimeSpan containing the current time then create that:

var currentTime = new TimeSpan(DateTime.Now.Hours, DateTime.Now.Minutes, 0);

If you're saving to a database column that is an actual time data type, that's what you want.

As pointed out in the comments, there's a non-zero probability of the the hour ticking over between the two uses of DateTime.Now in the code above. To avoid that, you can introduce an additional variable or even reuse the same one:

var currentTime = DateTime.Now;

currentTime = new TimeSpan(currentTime.Hours, currentTime.Minutes, 0);

I almost mistakenly wrote VB to start with and was going to use a With block to create an implicit variable, but C# has no equivalent.

huangapple
  • 本文由 发表于 2023年5月14日 13:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定