Dates Comparison in asp.net - asp.net

I have two text boxes where i am populating them with calendar i,e I am getting dates into the textboxes in string format.
i,e string startdate=txtstartdate.text;
i,e string enddate=txtenddate.text;
now i need to compare these two dates.
my requirement is: enddata should be greaterthan startdate.
Kindly help me in this regard.

DateTime.TryParse is the safest way because it doesn't throw exceptions like DateTime.Parse. It returns true/false on the call so you can handle failures very simply.
string text1 = DateTime.Now.ToString();
string text2 = DateTime.Now.AddHours(-4).ToString();
DateTime d1;
if(!DateTime.TryParse(text1, out d1)) Console.WriteLine("Failed to parse text1");
DateTime d2;
if(!DateTime.TryParse(text2, out d2)) Console.WriteLine("Failed to parse text2");
if(d1 > d2) Console.WriteLine("d1 \"{0}\" is greater than d2 \"{1}\"", d1, d2);
else Console.WriteLine("d1 \"{0}\" is not greater than d2 \"{1}\"", d1, d2);
Also, I noticed several answers using Compare and I hardly ever use .Compare.

You need to parse them as dates and then compare them. Example:
DateTime sdate= DateTime.Parse(txtstartdate.Text);
DateTime edate = DateTime.Parse(txtenddate.Text);
if(sdate>edate)
{
Throw validation error;
}

Dim startDate As DateTime
Dim endDate As DateTime
Dim returnValue As Integer
returnValue = DateTime.Compare(startDate, endDate)
If returnvalue is:
Less than zero -> startDate is earlier than endDate.
Zero -> startDate is the same as endDate.
Greater than zero -> startDate is later than endDate.

if (DateTime.Parse(enddate).CompareTo(DateTime.Parse(startdate)) > 0) {
// enddate is later than startdate
}
That piece of code doesn't do any error checking. You may want to do error checking when parsing string into date.

Related

ASP .Net Razor: format substract of 2 DateTime to a string specific format

I've got 1 model.DateTime value (which is I'm getting from Database) and I want to represent model DateTime which is end time, and DateTime.Now as now time.
I want to format subtract of that 2 DateTime-s as a specific String format "dd:hh:mm:ss".
In your ASP .Net view page you can open razor block and you can calculate difference between 2 variables that are DateTime type.
#{
DateTime end = (DateTime)item.close_date_time;
DateTime now = DateTime.Now;
TimeSpan diff = end.Subtract(now);
}
Then you can simply convert TimeSpan diff to string:
#diff.ToString(#"dd\:hh\:mm\:ss")
And by that I've solved time difference and to format it to specific string.
EDITED
Simply you can do this:
DateTime CurrentDateTime = DateTime.Now;
item.duration.Subtract(CurrentDateTime).ToString(#"dd\:hh\:mm\:ss");
Hope this will help

Compare date part of datetime column with NamedQuery

I have a table containing entries with date and time. I try to create a NamedQuery which only compares the date part.
#NamedQuery(name = "Vote.findForDate", query = "SELECT v FROM Vote v WHERE v.createdAt = :date")
...
createNamedQuery("Vote.findForDate").setParameter("date", date, TemporalType.DATE).getResultList();
But it seems that it always tries to compare the whole datetime.
Is there no way without using date() function in SQL?
I try to be independent from the database. For example h2 has no date() function.
One possible solution is the usage of date as column type and reduce the information.
#Column(name = "voteDate")
#Temporal(value = TemporalType.DATE)
private Date voteDate;

How to insert null value for datetime field in asp.net?

I am trying to insert null value from front end. This is my code:
if (!string.IsNullOrEmpty(txtCallTwo.Text))
{
DateTime second = DateTime.ParseExact(txtCallTwo.Text.Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
objclsConsultantLeadStatusProp.dtDate_2nd_Call = second;
}
else
{
DateTime second = DateTime.ParseExact(txtCallTwo.Text.Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
objclsConsultantLeadStatusProp.dtDate_2nd_Call = null;
}
dtDate_2nd_Call property is declared as as Datetime.
You need to make dtDate_2nd_Call as nullable property. Syntax for nullable property is like this.
DateTime? dt = null;
For your case it should be Datetime? dtDate_2nd_Call instead of Datetime dtDate_2nd_Call
The answer to this question is pretty simple. I am not sure if it is of any help to you now...
The DateTime data structure in .NET does not accept null values and thus gives you the error, the simple solution to this is adding a question mark without spaces next to DateTime, i.e., DateTime?
DateTime? data structure accepts null values and thus you won't get the error.

How can I remove the Time from a DateTime value?

In my SQL database, I have a column formatted as DateTime and when I retrieve data from that column in ASP.NET, I catch it on the Date variable, than pass the value to textbox:
Dim Y As Date = dt.Rows(0)("SCH_DATE")
txtSchedDate.Text = Y.Date.ToString
but when I debug my website, the txtSchedDate.Text still gives me the full DateTime value:
7/17/2013 12:00:00 AM
is it possible to eliminate the time value here and just return the date?
Have you tried using something like
txtSchedDate.Text = Y.Date.ToString("MM/dd/yyyy")
or which ever format you wish to display.
Have a look at
DateTime.ToString Method (String)
Converts the value of the current DateTime object to its equivalent
string representation using the specified format.
Custom Date and Time Format Strings
Standard Date and Time Format Strings
Convert.ToDateTime(dt.Rows(0)("SCH_DATE")).ToString("M/d/yyy")
you can get date by txtSchedDate.Text = Y.Date.ToShortDateString()
Besides answers above, you can try converting it in SQL server
SELECT CONVERT(varchar(15), GETDATE(), 11)
Keep in mind after converting it's VARCHAR(15) instead of DATETIME.
Once you have a Date object, you can get the constituent pieces if you wish as well, like this:
Dim Y As Date = dt.Rows(0)("SCH_DATE")
txtSchedDate.Text = Y.Date.Year & "-" & Y.Date.Month & "-" & Y.Date.Day
Or you can use the custom and standard date and time format strings mentioned by others.

sql datetime to compare with string

if i have the following to access an sql database for a date to compare it to a string that a user enters:
public IQueryable<Audit> FindAllAuditsByNameDate(String name, String date)
{
return from audit in db.Audits
where audit.EventTime.ToString().Contains(date) && audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
}
it fails is the user enters the "/" character in a date. how do i work around this?
Try DateTime.Parse. It's able to understand a lot of the common formats for entering DateTimes.
DateTime dateStart = DateTime.Parse(date);
DateTime dateEnd = dateStart.AddDays(1);
return from audit in db.Audits
where audit.EventTime >= dateStart &&
audit.EventTime < dateEnd &&
audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
If DateTime.Parse doesn't parse the format you want, you can always use DateTime.ParseExact and provide your own format strings.
Considering EventTime is of type DateTime? you need to check it against its value. First convert the string date to DateTime
DateTime newDate = Convert.ToDateTime(date);
return from audit in db.Audits
where audit.EventTime.Value == newDate && audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
Warning - Don't use Contains.
Disadvantages of Contains
Suppose I have two list objects.
List 1 List 2
1 12
2 7
3 8
4 98
5 9
6 10
7 6
Using Contains, it will search for each List-1 item in List-2 that means iteration will happen 49 times !!!
Answer to your original Question
public IQueryable<Audit> FindAllAuditsByNameDate(String name, String date)
{
DateTime Dt;
if (DateTime.TryParse(date, out Dt))
{
return from audit in db.Audits
where audit.EventTime.ToString().Contains(date) && audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
}
return null;
}
TryParse
Returns a bool indicating whether it succeeded.
It just try/catch internally that why is implemented without exceptions so that it is fast.
Use it in case the value may be InValid.
Parse
Throws an exception.
Use it if you are sure the value will be valid

Resources