I have a Listview which fetches data from a SQL Database. One of the columns is a date which takes data from the database in the format "mm/dd/yyyy 0:00:00 AM"
I'm trying to get the date to highlight if its over an hour old from DateTime.Now
Here is what I have now (yes I know it's wrong)
Label TimeLabel = (Label)e.Item.FindControl("TPTIMEIN");
if (TimeLabel != null)
{
DateTime Total;
if (DateTime.TryParse(TimeLabel.Text, out Total) == true)
{
if (Total < (DateTime.Now))
{
TimeLabel.BackColor = System.Drawing.Color.Red;
TimeLabel.ForeColor=System.Drawing.Color.White;
}
}
}
Any help will be really appreciated, I'm quite new to coding so go easy on me!
Use DateTime.AddHours(1). See MSDN
if(Total > DateTime.Now.AddHours(1))
{
TimeLabel.BackColor = System.Drawing.Color.Red;
TimeLabel.ForeColor=System.Drawing.Color.White;
}
You can do
String dtFormat = "MM/dd/yyyy h:mm:ss tt";
String dtString = "02/01/2015 10:01:56 AM";
DateTime dtObject = DateTime.ParseExact(dtString, dtFormat, System.Globalization.CultureInfo.InvariantCulture);
if (dtObject.AddHours(1) >= DateTime.Now)
{
//Greater
}
else
{
// Smaller
}
if (DateTime.Now.Subtract(Total).TotalHours > 1)
{
//Change the label color here
}
Related
I have a gridview and I would like to highlight the days which has difference > 10.
What I have now
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime dateNow = DateTime.Now;
string dateCreated = e.Row.Cells[5].Text;
DateTime dc = Convert.ToDateTime(dateCreated);
TimeSpan difference = dateNow - dc;
if (difference.TotalDays > 0)
{
e.Row.BackColor = System.Drawing.Color.Cyan; // This will make row back color red
}
}
}
Date format of the one saved onto my database is dd-MM-YYYY and it is saved as nvarchar.
Use this:
int minutes = (int)DateTime.Now.Subtract(dc).TotalMinutes;
or days
int days = (int)DateTime.Now.Subtract(dc).TotalDays;
Or seconds, miliSeconds, Weeks, ....
To get date from your string do this:
string dateCreated = "01-01-2017";
string[] dcArray = dateCreated.Split('-');
DateTime dc = new DateTime(int.Parse(dcArray[2]), int.Parse(dcArray[1]), int.Parse(dcArray[0]));
You should parse DateTime like that:
DateTime dc = DateTime.ParseExact(dateCreated, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Victor Leontyev is right on with the parsing. But then you also have to tweak you logic:
if (difference.TotalDays > 0)
to
if (Math.Abs(difference.TotalDays) > 10)
i have 3 dropdownlist for dd,mm,yyyy.
how to restrict user to enter date greater than current date. ex 7 may 2015.
while giving input 7 may 2015 its giving invalid date. how to restrict user not to select dropdown item greater than current date
protected void btnTest_Click(object sender, EventArgs e)
{
DateTime date1 = DateTime.Now;
string dayNumber = date1.ToString("dd",
CultureInfo.InvariantCulture);
string MonthNumber = date1.ToString("MM",
CultureInfo.InvariantCulture);
string YearNumber = date1.ToString("yyyy",CultureInfo.InvariantCulture);
if (DDLDay.SelectedItem.Text != "DD" && DDLMonth.SelectedItem.Text != "MM" && DDLYear.SelectedItem.Text != "YYYY")
{
if (Convert.ToInt32(DDLYear.SelectedItem.Text) <= Convert.ToInt32(YearNumber))
{
if ((Convert.ToInt32(DDLMonth.SelectedItem.Value) <= Convert.ToInt32(MonthNumber)))
{
if ((Convert.ToInt32(DDLMonth.SelectedItem.Value) <= Convert.ToInt32(MonthNumber)))
{
}
else
{
Response.Write("not valid day ");
return;
}
}
else
{
Response.Write("not valid day");
return;
}
}
else
{
Response.Write("not valid day ");
return;
}
}
else
{
Response.Write("DOB Cannot blank");
}
}
string currentDate = DateTime.Now.ToString("d");
From your current code, you can easily construct a DateTime object and compare that:
DateTime selectedDate = new DateTime( Convert.ToInt32(YearNumber)
, Convert.ToInt32(MonthNumber)
, Convert.ToInt32(DayNumber)
);
if (selectedDate > DateTime.Now)
{
// error
}
You could use the built-in input type="date" in order to have a uniform way the date is formatted. It also supports a maximum date to select.
Why not straighforward > (or >=) between two dates (userInput and limit):
protected void btnTest_Click(object sender, EventArgs e) {
DateTime limit = DateTime.Now.Date;
DateTime userInput = new DateTime(
int.Parse(DDLYear.SelectedItem.Text),
int.Parse(DDLMonth.SelectedItem.Text),
int.Parse(DDLDay.SelectedItem.Text));
//TODO: it's unclear from the question if you want ">" or ">=", put right comparison
if (userInput >= limit) {
Response.Write("not valid day ");
return;
}
...
}
I am creating some schedule output using dateTimePicture in C# toolbox(Format of Short) on the datagrid. I just want is when the user choose the date "From" and "To" and click the button execute, the dategrid will automatically output the date starting "From" and end on "To". Any ideas? Please just comment your ideas below. Thank you guys!
Here's my code
private void btn_execute_Click(object sender, EventArgs e)
{
String from = date_from.Text;
String to = date_to.Text;
int count;
for(count = 0; count < to; count++)
{
dgv_result.Rows.Add(1);
dgv_result.Rows[count].Cells[0].Value = from;
}
}
Try this
var fromDate = DateTime.Now; // set here your from date
var toDate = DateTime.Now.AddDays(7); // set here your to date
for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
{
dataGridView1.Rows.Add(date);
}
EDIT:
If you are using DateTimePicker for toDate and fromDate then try this
var fromDate = date_from.Value; // Don't use date_from.Text as you mentioned in comments
var toDate = date_to.Value;
for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
{
dataGridView1.Rows.Add(date);
}
In my requirement, I am inserting the residential history details into the GridView...
It also contains FromDate & ToDate... So for first row, there is no condition..
On inserting second row, the FromDate & ToDate should not clash with my first row date range..
Is there any idea to avoid that????
FromDate ToDate Place
12/10/2012 12/05/2013 XXXXX
12/05/2004 12/09/2014 YYYYY
Second row should not be Allowed.. Bcoz in 2004 - 2014, already 2012 - 2013 time period is already mentioned.. So, this thing should not be added into the GridView
My Code:
protected bool ValidateResidenceDates(DateTime frmDate, DateTime toDate)
{
bool isValid = true;
DataTable dt = (DataTable)Session["ResidenceNew"];
if(dt != null)
{
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
DateTime dtFromDate = Convert.ToDateTime(dr["HKR_FromDate"], ci);
DateTime dtToDate = Convert.ToDateTime(dr["HKR_ToDate"], ci);
if (frmDate > dtFromDate && frmDate < dtToDate)
{
Com.MessageBox("From Date is Already Mentioned in the Residence History Date Range", UpdatePanel1);
SetFocus(txtResideFromDate);
isValid = false;
return isValid;
}
if (toDate > dtFromDate && toDate < dtToDate)
{
Com.MessageBox("To Date is Already Mentioned in the Residence History Date Range", UpdatePanel1);
SetFocus(txtResideToDate);
isValid = false;
return isValid;
}
}
}
}
return isValid;
}
You also need to check following scenario:
1) frmDate >= dtFromDate && toDate <= dtToDate
Let say there is already entry for 2003-2015 then user can not add 2004-2014
2) frmDate <= dtFromDate && toDate >= dtToDate
this is the case which you have mentioned. already added for 2012-2013 then user can not add 2004-2014
I'm using the code below to compare two Times:
DateTime systemtime = DateTime.Now;
DateTime timestart = Convert.ToDateTime(txtTimestart.Text);
DateTime timeend = Convert.ToDateTime(txtTimeend.Text);
if (systemtime < timestart || systemtime > timeend)
{
MessageBox.Show("not auth.");
}
else
{
MessageBox.Show("auth.");
}
But I also want to compare the current day. For example, if today is Monday or Thursday, the user is authenticated, not if otherwise. How do I do it? Thanks.
DateTime systemtime = DateTime.Now;
if(systemtime.DayOfWeek == DayOfWeek.Monday)
{
...
}
timestart.DayOfWeek will give you values like DayOfWeek.Thursday or DayOfWeek.Friday etc.
See here for documentation and an example: http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx
The DateTime object will have a property DayOfWeek.
You could just compare the string.
try this
var systemtime = DateTime.Now;
var start = "Monday";
var finish = "Wednesday";
DayOfWeek startDay;
if (!Enum.TryParse<DayOfWeek>(start ,out startDay))
{
//handle parse error
}
DayOfWeek finishDay;
if (!Enum.TryParse<DayOfWeek>(finish, out finishDay))
{
//handle parse error
}
if (systemtime.DayOfWeek < startDay || systemtime.DayOfWeek > finishDay)
{
MessageBox.Show("not auth.");
}
else
{
MessageBox.Show("auth.");
}