How to compare the database field and datetime in asp.net - c#

NET and I working on a program where I take some data from database and try to compare with the DateTime field.
For Example I have certain documents in the SEIBEL database and I want expiration date of those documents and compare the with current date and time and fire message accordingly. But somehow I an unable to compare them.
This is the sql query in asp.net that I am running
private static readonly string GET_PROVIDER_DOCUMENTS = #"
select sc.row_id,
doc.created as created_date,
doc.attrib_04 as document_type,
doc.attrib_47 as exipration_date,
att.row_id as document_row_id,
att.file_name || '.' || att.file_ext as file_name
from siebel.s_org_ext sc
join siebel.s_org_ext_xm doc
on doc.par_row_id = sc.row_id
and doc.type = 'SCLicenseInfo'
and doc.attrib_35 = 'Expiration Date'
and doc.attrib_04 in ('Certificate of Insurance', 'Master Service Agreement')
left join siebel.s_accnt_att att on att.comments = doc.row_id
where sc.row_id = :sc_row_id
";
and this where I trying to get expiration date from database
ExpirationDate = ConvertExpirationDate(dr["exipration_date"].ToString()),
If anybody has any idea about it it would great. Thanks in advance

Have you looked at the TryParse method on a DateTime object?
https://msdn.microsoft.com/en-us/library/system.datetime.tryparse(v=vs.110).aspx
May be suitable for your needs though I believe it will depend on the format your date is stored in.

Assuming you are successfully getting the datetime from the datebase and storing it as a string called ExpirationDate:
DateTime date1 = Convert.ToDateTime(ExpirationDate);
Datetime date2 = new Datetime(---)//desired date to compare with.
if(DateTime.Compare(date1,date2)==0)
{
// They're equal.
}
else
{
// Not equal.
}
Converting:
https://msdn.microsoft.com/en-us/library/system.convert.todatetime(v=vs.110).aspx
Comparing:
https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx

Alternatively you could compare the day / month / year components of the date like this :
DateTime today = DateTime.Today;
if(ExpirationDate.Year == today.Year &&
ExpirationDate.Month = today.Month && ExpirationDate.Day = today.Day )

Related

Get records of last week adding by datetime in database

I'm using asp.net MVC in my project. My database table includes some records. The table has datetime column for records. I want to get records of last week adding. So the LastlyRecords is:
DateTime.Now = 04.04.2015
LastWeekDateTime = 28.04.2015
LastWeekDateTime < LastlyRecords < DateTime.Now
Have a method that accepts a "Start Date" and "End Date" as parameters.
Call it with a start/end date like:
GetRecords(DateTime.Now.AddWeeks(-1), DateTime.Now);
For there, you can have a stored procedure fetch records between that date range (or do something similar for Entity Framework or whatever you're using).
You can do something similar in T-SQL via GETDATE() and DATEADD(), but it's arguably better to do the range calculation in the calling code (because it's more a business logic thing than a data access thing).
you have to write logic on your query or you can modify below as per your datetime range.
var lastweek = DateTime.Now.AddDays(7);
var records = d in db.Persons
where DateTime.Compare(lastweek, d.DateRecordColumn)
and DateTime.Compare(d.DateRecordColumn, DateTime.Now)
select d;
hope this help to resolve your query!!!
string dateTime = "01 April 2015 Wednesday 16:23";
DateTime time1 = Convert.ToDateTime(dateTime);
if (DateTime.Compare(DateTime.Now, time1) == 1 && // DateTime.Now > time1
DateTime.Compare(time1, DateTime.Today.AddDays((int)-7)) == 1 // time1 >= DateTime.Now-7days
)
{
#("True.")
}
else
{
#("False.")
}
The result is true, so it is in last week.

Unexpected Behavior of Date Parse on Azure

In short, I'm parsing a passed in date to get a date to be used in an EF query. It works as expected when testing locally, and reports it as the correct date minus one day when hosted in Azure.
The string form is 11/27/2013
To convert to dates I'm using:
var sDate = DateTime.Parse("11/27/2013").Date;
var eDate = sDate.AddDays(1);
Then in EF I'm using:
var res = from p in context.Table
where p.PlaceholderDate >= sDate &&
p.PlaceholderDate < eDate
select p;
I end up with data for 11/26/2013 when hosted on Azure, and 11/27/2013 on my local machine.
If helpful, my timezone is EST.
Any help would be appreciated.
Could you give DateTimeOffset.Parse a try? And then pass in the expected offset (change the +1:00 to whatever offset you require) just to be safe?
Like so?
// String with date and offset
dateString = "05/01/2008 +1:00";
offsetDate = DateTimeOffset.Parse(dateString);
Console.WriteLine(offsetDate.ToString());

How to get DateTime with a UTC datetime and a particular timezone?

My data in SQL database looks like this:
PubDateUTC PubDateUTCOffset
----------------------- --------------------
2011-08-04 10:02:50.000 +8:00:00
2012-04-23 02:32:25.287 +8:00:00
2010-09-26 04:23:00.000 +8:00:00
What I want is to get a DateTime based on PubDateUTC and PubDateUTCOffset, for example:
2011-08-04 10:02:50.000, +8:00:00 should result in 2011-08-04 18:02:50:000
I have tried with TimeZoneInfo class, but I don't know hot to create a instance of TimeZoneInfo with a string like "+8:00:00", which would be the CreateTimeZoneInfo method below
var tz = CreateTimeZoneInfo(post.PubDateUTCOffset);
return TimeZoneInfo.ConvertTimeFromUtc(post.PubDateUTC, tz);
Is there anyway to do this?
Note: I cannot change the data in SQL database.
You could try something like:
var date = post.PubDateUTC.Add(
TimeSpan.Parse(post.PubDateUTCOffset.Replace("+", ""))
);
The .Replace("+", "") is because TimeSpan will handle -01:00:00 but will choke on +01:00:00
I think you need to use DateTimeOffset class. This thread may be helpful.
http://msdn.microsoft.com/en-us/library/bb546101.aspx
This works, remove any leading "+" from the offset ( "-" are ok)
var d = new DateTimeOffset(DateTime.Parse("2011-08-04 10:02:50.000"),
TimeSpan.Parse("08:00:00"));
d.DateTime - the time in db = 10:02:50
d.LocalDateTime - the time according to your servers timezone
d.UtcDateTime - the time at GMT = 02:02:50
I'm not sure you want 18:02:50 since it is the time at GMT+16 (+16:00:00), unless of course that is how it's encoded in the db, then just ignore this post :)
You should change your post class to have one property:
public DateTimeOffset Published { get; set; }
Then when you read from the database (assuming you have datetime and varchar types in your database):
DateTime utc = DateTime.SpecifyKind(
(DateTime) reader["PubDateUTC"], DateTimeKind.Utc);
TimeSpan offset = TimeSpan.Parse(
((string) reader["PubDateUTCOffset"]).Replace("+", ""))
post.Published = new DateTimeOffset(utc).ToOffset(offset);
Then when you need to consume it, you have all of the options of a full DateTimeOffset:
DateTime local = post.Published.DateTime; // with your offset applied
DateTime utc = post.Published.UtcDateTime; // the original utc value
string s = post.Published.ToString("o"); // 2011-08-04T18:02:50.0000000+08:00

C# MySQL LINQ DateTime conversion

I'm trying to retrieve records from a mySQL DB using LINQ and C#.
The date in c# code is a string: 23-01-2010
I need to convert this to DateTime format as 2010-01-23 (mySQL default DateTime format), otherwise the query does not return any records, at present it errors saying a string cannot be matched against a DateTime (row.DateOfIssue)
If I convert the string to DateTime (C#), then it is not in the mySQL DateTime format of yyyy-MM-dd
String endDate = "23-01-2010";
var query = (from row in uow.UserPersonalLicenseDetails
where (endDate >= row.DateOfIssue && endDate <= row.DateOfExpiry)
select row)
This is such a standard query it seems mad that it is so hard to do in LINQ.
It seems putting any method like CompareTo etc in the where clause causes an error of "Search for a class that works in this scenario"
I'm now wondering if the best line of attack might be to write a stored procedure in the database. This could then take the C# datetime as a parameter, convert it to mySQL format and then run the required query.....
Any thoughts?
Make it a DateTime - so
var myDate = DateTime.Parse(endDate);
Then
myDate.ToString("yyyy-MM-dd");
---------- or this:
var myDate = DateTime.Parse(endDate);
var query = (from row in uow.UserPersonalLicenseDetails
where ((myDate.CompareTo(row.DateOfIssue)>=0 && (myDate.CompareTo(row.DateOfExpiry)<=0)
select row
Just convert your date string to DateTime and then in the LINQ convert the string to DateTime that's coming back in order to do the comparison. I've used ParseExact because we need to make sure that we are parsing to the exact format that MySQL stores the date in, which is yyyy-MM-dd hh:mm.
Something like:
var endDate = DateTime.Parse("23-10-2010").ToString("yyyy-MM-dd hh:mm");
var formattedEndDate = DateTime.Parse(endDate);
//you could cut that to one line by putting the date in said format in the first place
var query = (from row in uow.UserPersonalLicenseDetails
where formattedEndDate >= row.DateOfIssue
&& formattedEndDate <= row.DateOfExpiry
select row)
Ok, problem was that the Table had the field defined as DATE rather than DATETIME so no match was being made.
Used DateTime.Date and the match was made.

Compare dates as strings

I can't find a way to find all the dates(strings) less then at least one year from now.
i keep in database Date Field strings like "DateTime.toShortDateString()" and i need to compare now.
it looks like month/day/year = 9/6/2011
its need to be lower at least one year from DateTime.now.
i did this and it doesnt return all dates needed just few.
DateTime Date = DateTime.Now;
int Year = Date.Year;
Year -= 1;
int Month = Date.Month;
string MonthYear = Month.ToString() + "%" + Year.ToString();
string Query = "SELECT * FROM Orders WHERE DateOrder < #STU ";
SqlCommand cmd = new SqlCommand(Query, con);
cmd.Parameters.AddWithValue("#STU", MonthYear);
This is my problem
Modify your database schema and store dates as char(10) in ISO 8601 format (yyyy-mm-dd) or the ISO 8601 compact form (yyyymmdd).
http://www.cl.cam.ac.uk/~mgk25/iso-time.html
http://en.wikipedia.org/wiki/ISO_8601
That gives you proper collation and proper comparison. Further...DateTime.Parse() and TryParse() will both accept that format regardless of culture (well..one exception: Saudi Arabia, ar-SA. Go figure). DateTime.ToString("Y") orstring.Format( "{0:Y}" , someDateTimeInstance )` will give you the ISO 8601 format.
Should be a simple update to your database.
Even better, if you're using SQL Server 2008: store dates using the new datatype Date.
Maybe deserialize these DateTime strings and then compare as DateTime objects?
var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
Then you can do:
if (dateToCompare1 < dateToCompare2)
Or whatever comparison operator you want.
Edit: from your comment, I think you would like use only dates that are later (or equal to?) one year from now. And so you would do:
var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
if (date >= DateTime.Now.AddYears(1) {
// Do whatever you want with the "kept" dates
}
Assuming you have a string:
string strDate1 = "09/06/2011";
string strDate2 = "09/06/2011";
DateTime date1 = DateTime.Parse(strDate1);
DateTime date2 = DateTime.Parse(strDate2);
Then compare them.

Categories