sql datetime to compare with string - asp.net

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

Related

Capture only month and year (or null) - then convert that to a date

I'm currently working with a client that has a VB.NET web application that was developed internally. They've got everything storing to an Access database which they cannot alter or change for their own reasons. I'm not familiar with any of these technologies, so I'm hoping you may have a solution.
The client has a date field that they are only capturing mm/yyyy or blank. They need this information to save to a datetime field in the database. I'm trying to work up a statement that will automatically take the date entered and convert from mm/yyyy to mm/01/yyyy if the date is provided, or 01/01/1970 if the field was left blank. Can anyone assist?
If we are talking about MS Access functions DateSerial is what you are looking for. The basic syntax is below. If the stored value is text you will need to use the Mid function to parse the text into the year and month and you can use use a hard coded 1 for the day.
DateSerial ( year, month, day )
This function can be used in a select or update. Additional logic will be required to provide a default value for the blank result. Typically in Access this type of logic is done with an IIF.
You can use a combination of the IIf,IsNull and CDate functions, like so:
IIf(IsNull([YourDateFField]),#1/1/1970#,CDate([YourDateFField]))
This tests if your field is null and if yes it returns 1/1/1970, if no it will convert your date string to an actual date (e.g. CDate("04/2014") will return 4/1/2014)
This (MSAccess/VBA) function will do what you are asking. If you pass-in a string like mm/yyyy, it will return a datetime like mm/01/yyyy. However, if the string does not fit that pattern (or equiv), the function will return a date time of 1/1/1970, like you asked.
'in MSAccess:
Public Function mmyyyyToDate(mmyyyy As String) As Datetime
If IsDate(Replace(mmyyyy, "/", "/01/")) Then
Return CDate(Replace(mmyyyy, "/", "/01/"))
Else
Return #1/1/1970#
End If
End Function
It would be more efficient to run it in MSAccess, but if you want to run it in VB.net instead, the syntax is different:
'in VB.NET
Public Function mmyyyyToDate(mmyyyy As Object, Optional defaultDate As DateTime = "1/1/1970") As DateTime
Dim re As DateTime
If Convert.IsDbNull(mmyyyy)
return defaultDate
ElseIf DateTime.TryParse(Replace(mmyyyy, "/", "/01/"), re) Then
Return re
Else
Return defaultDate
End If
End Function
Example of running it:
'MSAccess query syntax
INSERT INTO NewDateTable (NewDateColumn)
SELECT mmyyyyToDate(oldColumn) FROM OldTable
If you can't add a new function to the MSAccess DB, you could turn this function into an inline statement (by using an IIF), but it looks pretty ugly:
'MSAccess query syntax
INSERT INTO NewDateTable (NewDateColumn)
SELECT IIF(IsDate(Replace(oldColumn, "/", "/01/")), Replace(mmyyyy, "/", "/01/"), #1/1/1970#)
FROM OldTable

FlexBuilder dateField '01/01/1901'

I've a dateField in FlexBuilder that returns DateTime from WebService C# and SqlServer.
The dateField show all DateTime from SqlServer, but with Date 'Null', It shows '01/01/1901'
What I need to do to get the datetime instead of null in date field.
You can handle this case on database layer so that all clients of this stored procedure / query will get same default value in case of null.
here's an example:
SELECT name, ISNULL (dateofbirth, GETDATE() ) FROM user
GETDATE() will return today's (server's system) date instead.
of-course not a reasonable default in above example, and you might want to do date manipulations for calculating some default value. you can use these reference docs
I solved problem :
public function IsDateNull(date:Date):String`enter code here`enter code here
{
if (date && date.fullYear == 1901)
{
return null;
}
else
{
return dateTimeFormatter1.format(date);
}
}
<s:DateTimeFormatter id="dateTimeFormatter1"
dateTimePattern="EEEE, dd MMMM , yyyy "
dateStyle="long" locale="it-IT"
errorText="Invalid input value"
useUTC="false"/>
<mx:DateField id="sData_ComunicazioneOSDateField" selectedDate="{classeDati.sData_ComunicazioneOS}" labelFunction="IsDateNull" />
Thank you for the help!!!

Dates Comparison in 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.

Inserting current date and time in SQLite database

I want to create a table in SQLite in which one of the field is for date, in which date and time of current instance should save. Which data type should I use?
I'm planning to use 'timestamp'. How to insert current timestamp value to the field? Also how to write content values for this date field?
SQLite supports the standard SQL variables CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP:
INSERT INTO Date (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
The default data type for dates/times in SQLite is TEXT.
ContentValues do not allow to use generic SQL expressions, only fixed values, so you have to read the current time in Java:
cv.put("LastModifiedTime",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
INSERT INTO Date (LastModifiedTime) VALUES(DateTime('now'))
Use this site for further reference.
To get the current local(system) time, add the 'localtime' option:
select datetime('now', 'localtime');
I'm using timestamps a lot in my app. For me the best way to keep the timestamp is to convert it in milliseconds. After that it is easy to convert it to any locale.
If you need the current time use System.currentTimeMillis().
Content values are easy to use, you just and field and value, like:
ContentValues ins_reminder = new ContentValues();
ins_reminder.put("REMIND_TIMESTAMP", System.currentTimeMillis());
Since SQLite 3.38.0, there is a unixepoch() function that returns UNIX timestamp in integer. Does the same thing as strftime('%s').
References:
release log draft
check-in
In my case i wanted to have a timestamp with fractions of a second.
The keyword CURRENT_TIMESTAMP has only a precision of YYYY-MM-DD HH:MM:SS (see docs DEFAULT clause).
The function strftime() can return fractions of a second
Example to use strftime() in an INSERT
INSERT INTO YourTable (TimeStamp)
VALUES (strftime('%Y-%m-%d %H:%M:%S:%s'))
Comparison of CURRENT_TIMESTAMP and strftime()
SELECT 'CURRENT_TIMESTAMP' as Timestamp_Command,
CURRENT_TIMESTAMP as TimeStamp_Precision,
'only seconds' as Timestamp_Comment
UNION ALL
SELECT 'strftime(%Y-%m-%d %H:%M:%S:%s)' as Timestamp_Command,
(strftime('%Y-%m-%d %H:%M:%S:%s')) as TimeStamp_Precision,
'with fraction of a second' as Timestamp_Comment
Example to use it in c#
The following is based on bulk insert in sqlite with ado.net
public static void InsertBulk(SqliteConnection connection)
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var command = connection.CreateCommand();
command.CommandText =
#"INSERT INTO BulkInsertTable (CreatedOn, TimeStamp)
VALUES ($createdOn, strftime('%Y-%m-%d %H:%M:%S:%s'))";
var parameter3 = command.CreateParameter();
parameter3.ParameterName = "$createdOn";
command.Parameters.Add(parameter3);
// Insert a lot of data
// calling System.DateTime.Now outside the loop is faster
var universalTime = System.DateTime.Now.ToUniversalTime();
for (var i = 0; i < 15_000; i++)
{
parameter3.Value = System.DateTime.Now.ToUniversalTime();
// faster
// parameter3.Value = universalTime;
command.ExecuteNonQuery();
}
transaction.Commit();
}
connection.Close();
}

Date comparision using Linq

I have a DateTime type column named "CreatedDate" in my sql table, and am passing the value for this column by using "DateTime.Now" from my asp.net application....
The datas in my CreatedDate column are,
CreatedDate
-----------
2012-05-07 18:56:17.487
2012-05-07 18:56:28.443
2012-05-07 19:21:24.497
2012-05-14 15:22:04.587
I need to get the datas with this CreatedDate.
in my entity framework I tried the condition like
DataAccess.Entities dataEntities = new DataAccess.Entities();
DataAccess.Employee employee = dataEntities.Employees
.First(e => e.CreatedDate == DateTime.Today);
like this, I have data for this date(2012-05-14) , but the mininutes part differes (the DateTime.Today gives '2012-05-14 12:00:000' like this) here, and it shows error like, sequence contains no element....
How can I compare the 'Date' alone in Linq.....can anyone help me here,,,
Use the Date Property on the DateTime object
CreatedDate.Date==DateTime.Today
So your code will be
DataAccess.Employee employee=dataEntities.
Employees.First(e=>e.CreatedDate.Date==DateTime.Today);
Date Property returns the Date Component of the DateTime object and the time value set to 12:00:00 midnight (00:00:00).
Try this:
DataAccess.Employee employee =
dataEntities.Employees.First(e=>e.CreatedDate.Date==DateTime.Today)
I just declared two variable like
DateTime date1=DateTime.Now.Date;
DateTime date2=DateTime.Now.Date.AddDays(1);
and in the condition I used these variables like
DataAccess.Employee employee = dataEntities.Employees
.First(e => e.CreatedDate >= date1
&& e.CreatedDate < date2);
its working....

Resources