comparing date values for equality - c#

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
}

Related

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

How to check the date format in given structure

I have passing a date in query string as the format of 02-2014.and using this date I done the search.It is working and the result is perfect .but when I change the query string value in the browser then the error will showing.In this condition I need only some message,So how can we check the query string date value is in correct format.my code is
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Just use DateTime.TryParseExact with the format string MM-yyyy. This will tell you whether your input string is in the format you specified and if so, it returns the parsed DateTime object via an out parameter.
Try this:
DateTime date;
if (DateTime.TryParseExact(text, "MM'-'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}

how to Check datetime entered

I have a textBox where the user enters a datetime using a calendar, I am checking for whether the text box is empty or not by
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false)
How can I check whether the datetime entered is less or = to the current datetime
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false
&& DateTime.Parse(txt_SendAt.Text) <= DateTime.Now )
DateTime enteredDateTime;
if (!DateTime.TryParse(txt_SendAt.Text, out enteredDateTime))
{
Debug.WriteLine("User entered date time in wrong format");
}else
{
if(enteredDateTime <= DateTime.Now)
{
// less or equal
}
}
Parse or TryParse the text to DateTime, then compare to DateTime.Now
A few steps here, first check something is entered, as you have done, secondly, check it is actually a date, and lastly check against the desired date, as such:
var input = DateTextBox.Text;
if (!string.IsNullOrEmpty(input))
{
DateTime date;
if (DateTime.TryParse(input, out date))
{
if (date <= DateTime.Now)
{
//bingo!
}
}
}
Notice the TryParse for checking proper formatting of the input string as a date - using only Parse is a sure way to make your app go BANG!
You can parse your string input to a DateTime using the DateTime.Parse method, then run your comparison in the normal way.
Remember, Parse methods will throw a FormatException if the input is not directly castable to the required type. It may make more sense to go for the TryParse method if you have, for example, a free-text input.
var inputDate = DateTime.Parse(txt_SendAt.Text);
if (inputDate > DateTime.Now)
{
Console.WriteLine("DateTime entered is after now.");
}
else if (inputDate < DateTime.Now)
{
Console.WriteLine("DateTime entered is before now.");
}
Use one of the Parse or TryParse static methods of the DateTime class to convert the string to a DateTime and compare it to the current DateTime.
DateTime input;
if(DateTime.TryParse(txt_SendAt.Text,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out input))
{
if(input <= DateTime.Now)
{
// your code here
}
}
else
{
//not a valid DateTime string
}
if (!(string.IsNullOrEmpty(txt_SendAt.Text) && Datetime.Parse(txt_SendAt.Text)<=Datetime.Now)
{
/*code */
}
else
{
/*code */
}

How to compare two dates in 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
}
}

Categories

Resources