start_date
(格式为DD-MM-YYYY
)end_date
如果我从登录页面登录,我想检查当前日期是否在start_date
和end_date
之间;如果是的话,我可以登录。
如何在C#中进行比较.. asp.net ..?
我已成功在登录页面打印当前日期。
lblMsg.Text= DateTime.Now.ToString("dd-MM-yyyy");
我正在使用带有c#
的asp.net start_date end_date
8/2/2013 12:00:00 AM 10/2/2013 12:00:00 AM
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime startdate = DateTime.ParseExact(tbstartdate.Text.ToString().Trim(), "dd/MM/yyyy", provider);
DateTime enddate = DateTime.ParseExact(tbenddate.Text.ToString().Trim(),"dd/MM/yyyy",provider);
string sql = "INSERT INTO TimeTable(start_date,end_date)"
+ "VALUES (@startdate,@enddate)";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@startdate", SqlDbType.DateTime).Value = startdate;
cmd.Parameters.Add("@enddate", SqlDbType.DateTime).Value = enddate;
cmd.Prepare();
n = cmd.ExecuteNonQuery();
conn.Close();
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(DateTime.Now.ToString("dd/mm/yyyy"), "dd/MM/yyyy", provider);
// DateTime date=DateTime.Now.ToString("dd/mm/yyyy");
string query1 = "select * from TimeTable where ((start_date >= @date1 and End_date<= @date2) and UserType=@type)";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand com = new SqlCommand(query1, conn);
com.Parameters.Add("@type",dpusertype.SelectedItem.Text.ToString());
com.Parameters.Add("@date1",date);
com.Parameters.Add("@date2", date);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
`if(dt.Rows.Count&gt; 0)//比较表中的用户
{
FormsAuthentication.RedirectFromLoginPage(txtFcode.Text, Persist.Checked);
Response.Redirect("~/DeptCoordinator/DeptCoordinator_homepage.aspx");
}
日历System.Globalization.GregorianCalendar中不支持字符串表示的DateTime。 Desc`
答案 0 :(得分:3)
假设您已从表中加载了start_date和end_from。然后
var now = DateTime.Now.Date;
var allowLogin = start_date <= now && now <= end_date;
答案 1 :(得分:0)
DateTime.Ticks
将占用时间
使用.Ticks
上的DateTime
将您的日期转换为longs
然后只需使用简单的if stmt来查看您的目标日期是否介于。
var now = DateTime.Now.Date;
// Assuming you know d2 > d1
if (now .Ticks > start_date.Ticks && now.Ticks < end_date.Ticks)
{
// targetDt is in between d1 and d2
}
但我建议你在database
而不是c#
进行比较。
select
columnName1,
columnName2,
....
from
tableName
where
GETDATE() between start_date and end_date;
一些有用的链接: -
Selecting between two dates within a DateTime field - SQL Server
Check if datetime instance falls in between other two datetime objects