How to get Date Difference in textbox? - c#

I have two textboxes : TextBox1 and TextBox2 both have date.
I want to get date difference in third textbox, that is TextBox3.
My code is:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) - Convert.ToInt32(TextBox2.Text)).ToString());
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) - Convert.ToInt32(TextBox2.Text)).ToString());
}

Convert both input values to DateTime, as in
DateTime dt1 = DateTime.Parse(TextBox1.Text);
DateTime dt2 = DateTime.Parse(TextBox2.Text);
Then, subtract both to get a TimeSpan object:
TimeSpan ts = dt1 - dt2;
Then you can use the properties of ts to set the value of the third text box:
TextBox3.Text = ts.TotalDays.ToString();
I assume here that valid dates are input into both text boxes, otherwise you'll get an exception in the first line above. You can alternatively look into the ParseExact or TryParse/TryParseExact methods provided by the DateTime class.

DateTime d1 = TextBox1.Text!=string.Empty?Convert.ToDateTime(TextBox1.Text): DateTime.MinValue;
DateTime d2 = TextBox2.Text!=string.Empty?Convert.ToDateTime(TextBox2.Text):DateTime.MinValue;
TimeSpan tspan= d2-d1;
TextBox3.Text = tspan.TotalDays.ToString();

Try like this
DateTime d1 = Convert.ToDateTime(TextBox1.Text);
DateTime d2 = Convert.ToDateTime(TextBox2.Text);
TimeSpan span = d2-d1;
TextBox3.Text = span.TotalDays.ToString();

Related

Highlight wpf calendar alternately

When a date is selected in DatePicker tool or type one date in TextBox,
how do highlight wpf calendar cells every three dates after selected date alternately? (3 dates highlight, 3 dates not highlight and this continues..).
I used this code, but intervals select one day every 3 days on MontlyCalendar:
DateTime a = new DateTime();
a = DateTime.Parse(myDatePicker1.Text);
DateTime h = new DateTime();
h = DateTime.Parse(myDatePicker2.Text);
for (DateTime f = a; f < h; f=f.AddDays(3))
{
MonthlyCalendar.SelectedDates.Add(f);
}
I hope this solves your problem
private int cant = 0;
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (cant < 3)
{
//highlight
cant++;
}
else if (cant < 6)
{
//not highlight
cant++;
}
else
{
cant = 0;
}
}
This is my solution:
private void btnClick2_Click(object sender, RoutedEventArgs e)
{
string dateString1, dateString2, format;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime t = DateTime.Parse(datePicker1.Text);
DateTime End = DateTime.Parse(datePicker2.Text);
DateTime g = t.AddDays(6);
TimeSpan ts = (g - t);
for (DateTime i = t; i <= End; i += ts)
{
DateTime r = i.AddDays(2);
dateString1 = i.ToString("MM/dd/yyyy");
dateString2 = r.ToString("MM/dd/yyyy");
format = "d";
DateTime a = DateTime.ParseExact(dateString1, format, provider);
DateTime b = DateTime.ParseExact(dateString2, format, provider);
myCalendar.SelectedDates.AddRange(a, b);
}
}

Comparing two dates one from the database and datetime.now

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)

C# - Execute on Datagrid the Selected Date From and To

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);
}

Limit hour DateTimePicker to 30 minute intervals [duplicate]

This question already has answers here:
How to contol the time interval in a DateTimePicker
(6 answers)
Closed 8 years ago.
I have several DateTimePicker controls in C# and I need to limit the user to only choose from 30 minute intervals, e.g. 9:00 --> 9:30 --> 10:00 --> 10:30, and so on. Is this possible?
public Form1()
{
InitializeComponent();
if (dt.Minute % 30 > 15)
{
initialValue = true;
dateTimePicker1.Value = dt.AddMinutes(dt.Minute % 30);
}
else
{
initialValue = true;
dateTimePicker1.Value = dt.AddMinutes(-(dt.Minute % 30));
}
_prevDate = dateTimePicker1.Value;
}
private DateTime _prevDate;
private bool initialValue = false;
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if(initialValue)
{
initialValue = false;
return;
}
DateTime dt = dateTimePicker1.Value;
TimeSpan diff = dt - _prevDate;
if (diff.Ticks < 0)
dateTimePicker1.Value = _prevDate.AddMinutes(-30);
else
dateTimePicker1.Value = _prevDate.AddMinutes(30);
_prevDate = dateTimePicker1.Value;
}
This should work. You need global variable/Property to store _prevDate. You set the _prevDate in Form1() or on Form Load.
How we are adding/removing 30 minutes every time.
On value Change event you are taking the current dataPicker Value, after that you calculate the difference between currentValue and prevValue. If the value > 0 Add, and value<0 Remove.
If you don't know how to change the DatePicker to show minutes you need this to add in the designer.
You need this code:
this.dateTimePicker2.CustomFormat = "dd/MM/yyyy hh:mm";
this.dateTimePicker2.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.dateTimePicker2.ShowUpDown = true;
EDIT:
I add the code which will start the DataPicker on 00 or 30 depending how close is to 30 or 00. You need another global variable of type bool which will put initialValue of the dateTimePicker. See the code.

Telerik Rad Calendar - Is Changing Data Source Possible?

I'm trying to change the dates displayed in a RadCalendar. For example, I want it to begin 2 weeks before the current date and ends two weeks after the current date. Is it possible?
I was able to change the text displayed in the cells (to display the "new" date) but the "OnClick" methods still sends the "old" date.
OnDayRender I added :
e.Cell.Text = "" + _calStartDate.Day.ToString() + "";
_calStartDate = _calStartDate.AddDays(1);
But the calendar still thinks that the new dates are the old one, so the "SelectedDate" method returns the "old" date and the date selected is not the current date.
Is there a way to just pass a new list of dates, which would be easier?
UPDATE / Solution:
I was able to make it work like that:
private int rowCounter = 0;
private int rowHeaderCnt = 0;
private DateTime _startDate;
private DateTime _endDate;
private DateTime _calStartDate;
private DateTime _calEndDate;
protected void radCalendar_DayRender(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
{
TableRow tr = (TableRow)e.Cell.Parent;
Table table = (Table)tr.Parent;
if (e.Day.Date.CompareTo(_calStartDate) < 0)
{
((TableRow)(e.Cell.Parent)).Style["display"] = "none";
}
else if (e.Day.Date.CompareTo(_calEndDate) > 0)
{
((TableRow)(e.Cell.Parent)).Style["display"] = "none";
}
else if (e.Day.Date.DayOfWeek == DayOfWeek.Sunday)
{
// This part will change the week number cell (if you don't display it, hide this part)
rowCounter++;
TableCell cellRowHeader = ((TableRow)(e.Cell.Parent)).Cells[0];
cellRowHeader.Text = rowCounter.ToString();
}
}
protected void Page_Load(object sender, EventArgs e)
{
radCalendar.RangeMinDate = _startDate;
radCalendar.RangeMaxDate = _endDate;
}
protected void radCalendar_HeaderCellRender(object sender, Telerik.Web.UI.Calendar.HeaderCellRenderEventArgs e)
{
if (e.HeaderType == Telerik.Web.UI.Calendar.HeaderType.Row)
{
rowHeaderCnt++;
e.Cell.Text = " " + rowHeaderCnt;
}
if (e.HeaderType == Telerik.Web.UI.Calendar.HeaderType.Column)
{
TableRow row = ((TableRow)(e.Cell.Parent));
row.Cells[0].Text = " " + StringUtil.getStringByLanguage("Week", "Sem.") + " ";
}
}
protected void raCalendar_SelectionChanged(object sender, Telerik.Web.UI.Calendar.SelectedDatesEventArgs e)
{
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
String url = String.Empty;
if (e.SelectedDates.Count == 1)
{
startDate = e.SelectedDates[0].Date;
endDate = e.SelectedDates[0].Date;
}
else
{
startDate = e.SelectedDates[0].Date;
endDate = e.SelectedDates[e.SelectedDates.Count - 1].Date;
}
// ... add code here with startDate and endDate
}
public void initCalendar(DateTime startDate, DateTime endDate)
{
this._startDate = startDate;
this._endDate = endDate;
this._calStartDate = startDate;
this._calEndDate = endDate;
while (this._calStartDate.DayOfWeek != DayOfWeek.Sunday)
{
this._calStartDate = this._calStartDate.AddDays(-1);
}
while (this._calEndDate.DayOfWeek != DayOfWeek.Saturday)
{
this._calEndDate = this._calEndDate.AddDays(1);
}
}
Based on my attempts, you can get very close to this setup. You have to use some trickery though, as the functionality, as far as I can tell, is not built into the calendar to only display the dates as you have asked for.
On page load:
protected void Page_Load(object sender, EventArgs e)
{
RadCalendar1.RangeMinDate = DateTime.Now.AddDays(-14);
RadCalendar1.RangeMaxDate = DateTime.Now.AddDays(14);
RadCalendar1.FirstDayOfWeek = (FirstDayOfWeek)DateTime.Now.AddDays(-14).DayOfWeek;
}
On day render:
protected void RadCalendar1_DayRender1(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
{
if (e.Day.Date >= RadCalendar1.RangeMinDate.Date && e.Day.Date <= RadCalendar1.RangeMaxDate.Date)
{
e.Cell.Visible = true;
}
else
{
e.Cell.Visible = false;
}
}
This will get you an initial calendar load that shows 2 weeks back and 2 weeks forward and only allow the user to select inside that date. What it does not do, and I'd guess to be a separate question, is it does not execute the hiding of the dates outside the range when you page to the following month.
You must be aware that the format for the calendar must be 42 days, as per the design of the tool itself. That is why you see the blank line on top, as we are hiding those days. To my knowledge you can not remove them, only hide them or display them but not allow them to be clicked.

Categories

Resources