【问题标题】:date range checking in C#C#中的日期范围检查
【发布时间】:2019-01-15 10:31:27
【问题描述】:

如何查找输入中的日期是否在特定日期范围内(例如,过去 7 天,意思是我会说 -7)。如果是在过去 7 天内,做某事,否则做其他事情。

我目前可以做到这一点,但我不知道如何进一步改变它以满足我的需求。

string a = "-1"; // These are values that are configurable based on which date is checked. Yesterday means, -1 for example. 
string b = "-15"; // -15 means within last 15 days.

DateTime d = input;
DateTime e = d.AddDays(int.Parse(a));
if (d is between datetime.now and e)
{
   //do something
} 
else do something

【问题讨论】:

  • C#中没有between类型操作。您需要执行d >= lowerLimit && d <= upperLimit(替换为<>,具体取决于范围是独占而不是包含)。
  • @Richard:理查德,伙计,我知道。我写了一个算法,想知道如何把它翻译成 C# 哈哈。我会为您的评论竖起大拇指 :D :D :D

标签: c# .net datetime c#-4.0 compare


【解决方案1】:

首先,使用有意义的名称而不是ab,其次:使用正确的数据类型(你根本不使用b):

int dayOffset = -1;
int lowerBound = -15;

var currentDate = DateTime.Now;

if(input >= currentDate.AddDays(dayOffset) && input <= currentDate)
{ // do smoething }

使用你的名字:

var currentDate = DateTime.Now;

if(input >= currentDate.AddDays(a) && input <= currentDate)
{ // do smoething }

【讨论】:

  • 伙计,你的回答让我非常困惑,无法重做。好吧,我在项目中使用了正确的微软标准命名约定,这里我举了一个例子,并且很容易重新定义。我是外行,我无法理解偏移量或下限等......你只能带一个字符串。其次,谈到数据类型,它的业务规则,我们应该在该列中有多个数据,因此不可能将其作为 int。
  • 好的,非常感谢,但我恐怕一开始理解起来很复杂,除非你注意细节(花更多的精力去理解)
  • 我猜 if 语句中的 currentDate.AddDays() 部分对于@Learner 来说看起来很混乱
  • 我刚看到,是的。他还说根据我的变量,它不是。你(Ozan Topal)根据我的变量写了,太引人注目了。无论如何,谢谢你们。 Ozan,我有一个问题要问你,请澄清
【解决方案2】:

基本可以使用小于()运算符。

我的意思是你应该改变你的 if 条件:

if (d >= e && d <= DateTime.Now)

【讨论】:

  • 我认为你的对我来说非常可重复,希望它不会抛出任何 null ref 异常或任何类型的异常?它在所有情况下都始终健壮吗?
  • 您需要确保您等待可解析为整数的字符串 a 具有可接受的值。如果是用户的输入,你应该考虑使用 int.TryParse 方法。
  • 伴侣,它不是来自用户的输入,它来自数据库。然而,它可以有空值(在最坏的情况下,因为该列可以为空,如果没有值,我们就放空)。在那种情况下会发生什么?例外还是好事?
  • d 是唯一的输入
  • 如果您尝试访问具有空值的变量,您将得到 ArgumentNullException。你应该决定在这种情况下该怎么做。
【解决方案3】:

您可以尝试这样的方法来比较没有TimeDate 部分

string a = "-1"; // These are values that are configurable based on which date is checked. Yesterday means, -1 for example. 
string b = "-15"; // -15 means within last 15 days.
DateTime d = new DateTime();
DateTime e = d.AddDays(int.Parse(a));
if (DateTime.Now.Date >= d.Date && e.Date <= d.Date)
{

}

【讨论】:

  • 谢谢你,易卜拉欣。为什么要使用 Date 组件?为什么不能没有呢?
  • 只比较没有时间的日期
猜你喜欢
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多