how to get only current date - c#

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

Related

c# Web app How to get no of working days exclude weekends and public holidays

Background information
Just starting out to learn C#, im trying to build a simple web app that calculate the no of working day(s) between 2 dates.
The UI of the web app
The basic logic is when the user input a date (ie 01/05/2018) and click the button.It will calculate the total number of working day (exclude weekends and public holidays).
The problem now is the calculation isnt accurate ie between 23/05/2018 & 31/05/2018 it shows 6, it should be 7 days. And it doesnt take the dates into consideration during calculation
namespace testtest
{
public partial class First : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//on btn click
protected void Button1_Click(object sender, EventArgs e)
{
string dt = TextBox1.Text;
DateTime dtDDMMYYYY = ParseDate(dt);
string dt2 = TextBox2.Text;
DateTime dtDDMMYYYY2 = ParseDate(dt2);
List<DateTime> list = new List<DateTime> {
DateTime.ParseExact("04/05/2018", "dd/MM/yyyy",
CultureInfo.InvariantCulture) };
DaysLeft(dtDDMMYYYY, dtDDMMYYYY2, true, list);
}
public DateTime ParseDate(string date)
{
DateTimeFormatInfo dateFormatProvider = new DateTimeFormatInfo();
dateFormatProvider.ShortDatePattern = "dd/MM/yyyy";
return DateTime.Parse(date, dateFormatProvider);
}
public int DaysLeft(DateTime startDate, DateTime endDate, Boolean
excludeWeekends, List<DateTime> excludeDates)
{
int count = 0;
for (DateTime index = startDate; index < endDate; index =
index.AddDays(1))
{
if (excludeWeekends && index.DayOfWeek != DayOfWeek.Sunday &&
index.DayOfWeek != DayOfWeek.Saturday)
{
bool excluded = false; ;
for (int i = 0; i < excludeDates.Count; i++)
{
if (index.Date.CompareTo(excludeDates[i].Date) == 0)
{
excluded = true;
break;
}
}
if (!excluded)
{
count++;
}
}
}
result.Text = count.ToString();
return count;
}
}
}
Keep it simple
public int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, List<DateTime> excludeDates) {
int count = 0;
for (DateTime index = startDate; index <= endDate; index = index.AddDays(1)) {
if (excludeWeekends && (index.DayOfWeek == DayOfWeek.Sunday || index.DayOfWeek == DayOfWeek.Saturday))
continue;
if (excludeDates.Contains(index.Date))
continue;
count++;
}
return count;
}
If the date is a weekend and excludeWeekends flagged, continue on to next date, if date is included in excludeDates continue, else count the day.

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

C# Cannot implicitly convert type 'string' to 'System.DateTime'

DateTime Time = DateTime.Now;
string format = "ddd";
Console.WriteLine(Time.ToString(format));
if (Time = "Mon; Tue; Wed; Thu; Fri;")
{
Console.WriteLine("It is a week day");
}
else
{
Console.WriteLine("it is a weekend");
}
I'm trying to get this code to check for the date and the display a response based on the day. Sorry if this is a simple question but I'm new to coding and I cant find a solution anywhere
You can do it like this.
bool isWeekDay == DateTime.Today.DayOfWeek > DayOfWeek.Sunday
&& DateTime.Today.DayOfWeek < DayOfWeek.Saturday;
if (isWeekDay) {
Console.WriteLine("It is a week day");
}
else {
Console.WriteLine("it is a weekend");
}
try
DateTime Time = DateTime.Now;
string format = "ddd";
Console.WriteLine(Time.ToString(format));
string day = Time.ToString(format);
if (day = "Mon; Tue; Wed; Thu; Fri;")
{
Console.WriteLine("It is a week day");
}
else
{
Console.WriteLine("it is a weekend");
}

how to get the total selected days from 2 calendars in asp.net

just like in my questions, i have 2 calendars to be selected by users, and i would like to get the total selected days and be displayed in label.
users have to select the start date in lstartdate calendar and end date in lenddate calendar.
private void ValidateDate()
{
if (lstartdate.Text == "" || lenddate.Text == "")
{
lwarndate.Visible = true;
lwarndate.Text = "Dates required";
}
if (lstartdate.Text != "" || lenddate.Text != "")
{
if (cstart.SelectedDate > cend.SelectedDate)
{
lwarndate.Visible = true;
lwarndate.Text = "Start date must be earlier than end date!";
}
if (cstart.SelectedDate <= cend.SelectedDate)
{
lwarndate.Visible = false;
}
if (cend.SelectedDate != null && cstart.SelectedDate != null)
{
Double Value;
if (cend.SelectedDate >= cstart.SelectedDate)
Value = (cend.SelectedDate - cstart.SelectedDate).TotalDays;
else
Value = (cend.SelectedDate - cstart.SelectedDate).TotalDays;
total.Text = // ?
}
}
}
im not sure if the code arrangements are correct or not. do help and tq :)
TRY LIKE THIS
DateTime DtF = ceFromDate.SelectedDate.Value;
DateTime D1T = ceToDate.SelectedDate.Value;
double dd = (DtF - D1T).TotalDays;
total.Text = dd.ToString();
Here is simple way to get different between two dates
class Program
{
static void Main(string[] args)
{
System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
Console.ReadLine();
}
}
Source
you need to implement it yourself..
Convert the difference between the two dates into a TimeSpan, then get the amount of Days of that TimeSpan and set this as your text-value.
private void ValidateDate()
{
if (lstartdate.Text == "" || lenddate.Text == "")
{
lwarndate.Visible = true;
lwarndate.Text = "Dates required";
}
if (lstartdate.Text != "" || lenddate.Text != "")
{
if (cstart.SelectedDate > cend.SelectedDate)
{
lwarndate.Visible = true;
lwarndate.Text = "Start date must be earlier than end date!";
}else{
lwarndate.Visible = false;
}
if (cend.SelectedDate != null && cstart.SelectedDate != null)
{
TimeSpan duration = DateTime.Parse(cend.SelectedDate ).Subtract(DateTime.Parse(cstart.SelectedDate ));
total.Text = duration.Days.ToString();
}
}
}

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