日期时间转换/魔法
有没有一种简洁的方法可以用 C# 编写这个逻辑?
if ((DateTime.Now >= "8:00 AM") && (DateTime.Now < 5:00 PM))
{// do something}
我正在制作一个演示应用程序,我想在工作日做一些事情,但我不希望这段代码太突出(大量转换=糟糕)。 (因为我希望我的演示内容更容易看到。
Is there a nice concise way to write this logic in C#?
if ((DateTime.Now >= "8:00 AM") && (DateTime.Now < 5:00 PM))
{// do something}
I am making a demo app where I want to make something happen in the work day, but I don't want this code to stand out much (a lot of casting = bad). (Because I want my demo stuff to be easier to see.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,你可以这样做:
请注意,我通常更喜欢只使用
DateTime.Now
属性一次,将结果复制到上面的局部变量中 - 这样你就不会'由于呼叫之间的时间变化,不会出现奇怪的可能性。这里不是问题,但在其他情况下可能会出现问题。如果您想以这种方式处理事情,另一种可能性是使用
DateTime.TimeOfDay
。我认为上面的内容已经很简单了。编辑:史蒂文指出我改变了 &&按照你原来的逻辑 || - 你原来的逻辑永远不会起作用,因为它永远不可能在上午 8 点之前和下午 5 点之后。上面的内容适用于“如果不是在工作日” - 如果您想要“如果是在工作日”,您只需要:
Well, you could do:
Note that I generally prefer to only use the
DateTime.Now
property once, copying the result into the local variable as above - that way you don't get odd possibilities due to the time changing between calls. Not a problem here, but it could be in other cases.Another possibility is to use
DateTime.TimeOfDay
if you want to handle things that way. I think the above is about as simple as it gets though.EDIT: Steven pointed out that I changed the && in your original logic to || - your original logic can never work, as it can never be before 8am and after 5pm. The above works for "if it's not in the working day" - if you want "if it is in the working day" you just need:
我想你想在这里做的是这样的:
I think what you want to do here is something like this:
如果你想让它变得“漂亮”,你还可以使用扩展方法:
If you wanted to make it "pretty" you could also use an extension method:
如果您可以将字符串格式化为当前日期和开始/结束时间的正确格式,则可以使用类似的内容。
我仍然认为使用其他人发布的小时方法更干净,但这种方法提供的答案类似于您提出问题的方式。
If you can format a string in the right format for the current date and start / end times you can use something like this.
I still think it's cleaner to use the hour method posted by others, but this is a method that provides an answer similar to how you asked your question.