简体   繁体   English

C#中的日期范围检查

[英]date range checking in C#

How to find if a date in the input is within a specific daterange (let's say for example wihtin last 7 days, meaning I will say -7). 如何查找输入中的日期是否在特定日期范围内(例如wihtin最近7天,这意味着我会说-7)。 If it is within last 7 days, do something, else do something else. 如果在最近7天内,请执行其他操作。

I currently could do upto this, but I don't know how to change this further to meet what I want. 我目前可以做到这一点,但是我不知道如何进一步改变以满足我的需求。

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

First of all, use meaningful names instead of a and b , secondly: use proper data types (you don't use b at all): 首先,使用有意义的名称而不是ab ;其次:使用适当的数据类型(根本不用b ):

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

var currentDate = DateTime.Now;

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

Using your names: 使用您的名字:

var currentDate = DateTime.Now;

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

You can use less than(<) and greater than(>) operator basicly. 基本上可以使用不到(<)和大于(>)运算符。

I mean you should change your if conditionlike: 我的意思是您应该更改您的if条件:

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

You can try something like this to compare Date portion without Time 您可以尝试使用类似方法比较没有Time Date部分

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)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM