How to compare two dates in c# - c#

I have a textbox where i will enter date in mm/dd/yyyy format,i want to compare this textbox date with current date(sysdate) in javascript code in c#.How to do that??Example i enter 11/11/2011 which is future date and it must be checked with sysdate and print an message

example
DateTime.ParseExact(txtDate.Text, "mm/dd/yyyy",null) > DateTime.Today

DateTime dateValue;
string dateString = textBox.Text;
if (DateTime.TryParse(dateString, out dateValue))
{
// Use Date.CompareTo as you want to...
int result = DateTime.Compare(dateValue, DateTime.Today);
if (result > 0)
{
//Future Date
}
}

Related

comparing date values for equality

I have a text box where user enters date in format "YYYY-MM-DD". I have to check whether the entered date is current date as per the server date. If both the date matches then only proceed further. I have to check only the date not date time.
<input type="text" class="form-control input_text" runat="server" id="englishDate9"/>
So how can I check this, is it possible to use asp validator or I have to do it from code behind?
#region date check section
string sysDt = englishDate9.Value;
DateTime oDate = DateTime.Parse(sysDt).Date;
DateTime sysdate = DateTime.Now.Date;
if(oDate == sysdate)
{
// show message
}
#endregion
I am using this code, but I am confused is this the correct code or not although for now it is giving correct result for me?
Hope this will help.
DateTime oDate;
if(DateTime.TryParse(englishDate9.Value, out oDate))
{
if(oDate != DateTime.Today)
{
return;
}
}
else
{
return;
}
You should do like this. because string any be anything thing other than the valid date and the required format.
string dateString = "2009-06-20";
DateTime dt;
bool isValid = DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
DateTime sysdate = DateTime.Now.Date;
if (isValid == true && DateTime.Now.Date == sysdate)
{
//Do something
}

How to compare date in format "dd/mm" with DateTime.Now

Please advise how I can check that current date (DateTime.Now) is in diapason of dates in format "dd/mm". For example - 01.01 <= DateTime.Now <= 01.03 - Current date more that 1st of January but less that 1st of March
Let dateStrFrom be the first input ie, the From Date and dateStrTo be the second input ie, the To date. Then you can use DateTime.TryParseExact to convert it into the required DateTime Object for processing your comparison.
I hope that you are looking for something like this :
string dateStrFrom = "01.01";
string dateStrTo = "01.03";
DateTime dateFrom, dateTo;
DateTime.TryParseExact(dateStrFrom, "dd.MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateFrom);
DateTime.TryParseExact(dateStrTo, "dd.MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTo);
if (dateFrom <= DateTime.Now && dateTo <= DateTime.Now)
{
// code here this will be the true condition for you
}
DateTime dt1 = DateTime.ParseExact("01/01", "dd/MM",null);
DateTime dt2 = DateTime.ParseExact("28/11", "dd/MM", null);
if (dt1 <= DateTime.Now && DateTime.Now < dt2)
{
MessageBox.Show("hi");
}
if someone find the solution, thanks
Try this:
DateTime.Compare(DateTime.Now, DateTime.ParseExact("01.03", "dd.MM", null))
This returns a signed number indicating the relative values of t1 and t2.Value Type Condition Less than zero t1 is earlier than t2. Zero t1 is the same as t2. Greater than zero t1 is later than t2.
You can parse using DateTime.Parse(). For your case you can using the DateTime.Compare()
Sample code will help you.
// If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/11/2016");
DateTime d2 = DateTime.Parse("01/01/2016");
if (d1.Date > d2.Date)
{
// do the stuff
}
// For Converting it to String
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
// Comparison
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
// Will give you a DateTime typed object
var dateTime = DateTime.Parse("01/01/2016");

c# check date is weekend or weekday

DayOfWeek today = DateTime.Today.DayOfWeek;
if (today == DayOfWeek.Sunday || today == DayOfWeek.Saturday)
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" weekend"');", true);
}
else
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" weekday"');", true);
}
From line above i am able to find if today is weekend or weekday
now i want to get the date from user input
i tried this but fail,
my text input format : 2016-10-04
string dateInput = dateTextbox.Text;
DayOfWeek today = DateTime.dateInput.DayOfWeek;
Use DateTime.ParseExact to parse your string into a DateTime
string dateInput = dateTextbox.Text; //"2016-10-04"
DateTime dtResult = DateTime.ParseExact(dateInput, "yyyy-MM-dd", CultureInfo.InvariantCulture);
DayOfWeek today = dtResult.DayOfWeek;
IMO, you should use some DateTime control instead of a TextBox to enter DateTime. till then you need to convert TextBox Text to DateTime object first.
DateTime dt = DateTime.ParseExact(dateTextbox.Text,
"YYYY-MM-DD",
CultureInfo.InvariantCulture);
FYI, there are numerous ways to convert String to DateTime (google will help). All have their pros and cons. Use which best suits you.

Convert string to dd/mm/yyyy in C# WPF

I have a value (as a date) that gets returned from the selected combobox item. I wish to convert this value to a proper DateTime string. Problem is the string from the combobox.selectedItem to convert is;
July 2016
and I want to convert it to (start of month always);
01/07/2016 12:00AM
Is there away of doing the in C#?
As the only way around it is to do I can think of;
if(combobox.selectedItem.Contains("July") && combobox.selectedItem.Contains("2016")) {
//startDate = Set date to 01/07/2016..
endDate = DateTime.Now().ToString();
}
which is not ideal at all...especially if I want do past 24+ months (as combobox is populated with each month between two dates from an xml file)
EDIT/UPDATE
See below working code based of the advice from BOB!
#region try set Date from selected background populated Month
try
{
//param/arg from backgroundWorker
string selectedDate = filterByMonthComboBoxParam;
//Could also be from direct combobox.selecteditem with system string removed
//string selectedDate = filterByMonthComboBox.SelectedItem.ToString().Replace("System.Windows.Controls.ComboBoxItem:", "");
for (int ifilterByMonthComboBox = 0; ifilterByMonthComboBox < filterByMonthComboBox.Items.Count; ifilterByMonthComboBox++)
{
string _filterByMonthComboBox = filterByMonthComboBox.Items[ifilterByMonthComboBox].ToString();
if (_filterByMonthComboBox.Contains(selectedDate)){
DateTime dtX;
if (DateTime.TryParseExact(selectedDate, "MMMM yyyy", null, DateTimeStyles.AllowWhiteSpaces, out dtX))
{
// Parse success
Console.WriteLine(dtX);
checkMinDate = dtX.ToString();
checkMaxDate = nowTime.ToString();
Console.WriteLine("Date Filter is:");
Console.WriteLine("Min: " + checkMinDate);
Console.WriteLine("Max: " + checkMaxDate);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
}
}
}catch(Exception dateError){
Console.WriteLine(dateError);
}
#endregion try set Date from selected background populated Month
DateTime dt;
if (DateTime.TryParseExact("July 2016", "MMMM yyyy", null, DateTimeStyles.None, out dt))
{
// Parse success
Console.WriteLine(dt);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
Checkout DateTime.TryParseExact() and the formats
Edit:
If the date have white space, either use string.Trim() on it or change DateTimeStyles.None to DateTimeStyles.AllowWhiteSpaces

Converting an inputted string into a date

I have been trying to get a date conversion to wrok to convert from a string to a date I have looked at msdn and some other stack o questions but multiple ways have not worked. I am making a console app and it needs a valid date to check other dates. below is my current attempt.
string StartDate, EndDate;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
StartDate = DateTime.Parse(StartDate);
I currently set the variable StartDate and then set it a value depending on what the user enters and then it should change this to a date using the Parse
you are trying to assign the DateTime value to string StartDate, which is wrong. So change it like below:
string StartDate, EndDate;
DateTime date;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
date = DateTime.Parse(StartDate);
A string is not a DateTime and a DateTime not a String. So you might be able to parse a string to a date but you cannot use the string variable for the DateTime and vice-versa. You need two variables:
string startDateInput = Console.ReadLine();
DateTime startDate = DateTime.Parse( startDateInput );
Since this could fail if the input string is not a valid date you should use TryParse:
DateTime startDate;
bool validDate = DateTime.TryParse(startDateInput, out startDate);
if(validDate)
Console.Write("Valid date: " + startDate.ToLongDateString());
Try using Convert.ToDateTime();
Example:
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Use DateTime.TryParse()
Converts the specified string representation of a date and time to its
DateTime equivalent and returns a value that indicates whether the
conversion succeeded.
DateTime date;
if (!DateTime.TryParse("DateString", out date))
{
MessageBox.Show("Invalid string!");
}
You need to specify the Date Format.
Try This: Example format MM-dd-yyyy
Console.WriteLine("Input Start date Format -> MM-dd-yyyy");
string StartDate = Console.ReadLine();
DateTime YourDate = DateTime.ParseExact(StartDate,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);

Categories

Resources