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());
Related
I wrote code to get dates from database that are older than today by 5 days
but not working
Dates are stored in db as DateTime like this 2020-06-19 02:40:10.000
I appreciate your assistance thanks in advance
var ArTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Arab Standard Time");
DateTime ArTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, ArTimeZone);
DateTime Today_DateandTime = DateTime.Parse(ArTime.ToString("yyyy/MM/dd hh:mm:ss tt"));
var query3 = (from st in Db.Support_Teckets .......
where DbFunctions.DiffDays(Today_DateandTime, st.Created_Date) > 5
"Older than today by 5 days" - but you are comparing time part too. If you only need to compare date part then you can use the var DbFunctions.TruncateTime to truncate any time part.
I am guessing you do not have any error in your code but not getting the correct data. Then write the last part of the query as following:
var query3 = (from st in Db.Support_Teckets .......
where DbFunctions.DiffDays(DbFunctions.TruncateTime(Today_DateandTime),
DbFunctions.TruncateTime(st.Created_Date)) > 5
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 )
I can really use some help wrapping my head around a problem I'm having querying data according to a SQL Date field.
I am storing the Date in UTC format using the following code:
objFitCalendarDto.Day = objFitCalendarDto.Day.ToUniversalTime();
That line assigns the date to the model that is inserted into the db through Entity Framework.
Now, my query is supposed to retrieve a row based on a date. So, I should be able to get the row for today, tomorrow, yesterday, and so on.
To do this, I'm using the method to search between two dates, a start date and an end date as follows:
DateTime dayBegin = DateTime.Today.Date.AddDays(dayOffset);
DateTime dayEnd = DateTime.Today.Date.AddDays(dayOffset + 1);
The purpose of dayOffset is to specify which day. If Offset is 0, then I am searching for Today. If dayOffset is 1, then I am searching for rows with tomorrow's date.
Now, since I stored the data originally in UTC, I am assuming that I must search for it in UTC as well. So before executing my query, I convert the dates to UTC like so:
dayBegin = TimeZoneInfo.ConvertTimeToUtc(dayBegin);
dayEnd = TimeZoneInfo.ConvertTimeToUtc(dayEnd);
Then I execute my query like so:
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
f.DayAsDate >= dayBegin && f.DayAsDate < dayEnd
select f);
problem is, it doesn't work. I have a row with the date, "2016-01-26" when I look at it in SQL Manager. However, it only returns from a query on yesterday's date. Today is 2016-01-26, by the way. Clearly I'm not getting this UTC concept. Can anyone see what I'm doing wrong here? I was assuming that if I stored everything as UTC and then before querying I converted my dates for the query to UTC, that everything should work.
UPDATE
Let's try like this:
As soon as you are storing only date part (SQL 'date' type), you
need to compare also only dates.
Instead of
DateTime dayBegin = DateTime.Today.Date.AddDays(dayOffset);
dayBegin = TimeZoneInfo.ConvertTimeToUtc(dayBegin);
let's just do
DateTime dayBegin = DateTime.UtcNow.Date.AddDays(dayOffset);
dayBegin in that case will be date with time anyway (time is 12:00:00 AM). It means, we need to truncate it with DbFunctions. We need equality check here.
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
f.DayAsDate == DbFunctions.TruncateTime(dayBegin)
select f);
END OF UPDATE
I believe that problem is that you comparing dates with times. In your case you need to compare only dates, as far as I understand. As a solution - use DbFunctions TruncateTime function. It can be used within linq queries - like in your code.
https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions.truncatetime(v=vs.113).aspx
So, complete solution would be
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
DbFunctions.TruncateTime(f.DayAsDate) >= DbFunctions.TruncateTime(dayBegin) && DbFunctions.TruncateTime(f.DayAsDate) < DbFunctions.TruncateTime(dayEnd)
select f);
i am using a function which is taking date time over the internet from external server.
here is the function which i am using to get date and time without depend on user pc date time settings.
using NodaTime;
using NodaTime.Text;
using System.IO;
using System.Globalization;
public static DateTime GetFastestNISTDate()
{
var result = DateTime.MinValue;
DateTime utcDateTime = DateTime.MinValue;
// Initialize the list of NIST time servers
// http://tf.nist.gov/tf-cgi/servers.cgi
string[] servers = new string[] {
"nist1-ny.ustiming.org",
"nist1-nj.ustiming.org",
"nist1-pa.ustiming.org",
"time-a.nist.gov",
"time-b.nist.gov",
"nist1.aol-va.symmetricom.com",
"nist1.columbiacountyga.gov",
"nist1-chi.ustiming.org",
"nist.expertsmi.com",
"nist.netservicesgroup.com"
};
// Try 5 servers in random order to spread the load
Random rnd = new Random();
foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
{
try
{
// Connect to the server (at port 13) and get the response
string serverResponse = string.Empty;
using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
{
serverResponse = reader.ReadToEnd();
}
// If a response was received
if (!string.IsNullOrEmpty(serverResponse))
{
// Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
string[] tokens = serverResponse.Split(' ');
// Check the number of tokens
if (tokens.Length >= 6)
{
// Check the health status
string health = tokens[5];
if (health == "0")
{
// Get date and time parts from the server response
string[] dateParts = tokens[1].Split('-');
string[] timeParts = tokens[2].Split(':');
// Create a DateTime instance
utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
// Convert received (UTC) DateTime value to the local timezone
result = utcDateTime.ToLocalTime();
//return result;
return utcDateTime;
// Response successfully received; exit the loop
}
}
}
}
catch
{
// Ignore exception and try the next server
}
}
//return result;
return utcDateTime;
}
this variable result has local date time but i need to use Nodatime library where i will put my local date time variable result and also specify different timezone and Noda libraray will return local date and time of that timezone.
just guide me how to achieve it. i visit this url but still not clear how to incorporate Nodatime library and local time got from external server together to get another datetime based on different timezone.
looking for help with bit of sample code
thanks
EDIT
var wc = GetFastestNISTDate();
var pattern = InstantPattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
var parseResult = pattern.Parse(wc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
if (!parseResult.Success)
throw new InvalidDataException("...whatever...");
var instant = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
timezone translation is not working. i got the right date from this function GetFastestNISTDate(); and next i try to get local date and time of different timezone based on my first utc time but code return wrong time for London. i guess i am making mistake the code. can anyone see & help. thanks
EDIT 2
the samething i want to achieve by Nodatime library.
var wc = GetFastestNISTDate();
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(wc, cstZone);
the above code is giving more or less right time. just tell me how to replace my last 2 line using nodatime library. thanks
Edit 3
var wc = GetFastestNISTDate();
Instant now = Instant.FromDateTimeUtc(wc);
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
#John just tell me the above code is ok because u said
Don't convert the UTC DateTime to a local version - it's pointless and confusing
Use Instant.FromDateTimeUtc to convert a UTC DateTime to an instant
GetFastestNISTDate() returning datetime instance and here we just create noda instance from utc datetime using like this code `Instant now = Instant.FromDateTimeUtc(wc);`
does it solve the issue.
EDIT 4
#Matt Johnson : thanks a lot for redirecting me to a good library.
i would definitely like to work with that library to achieve my task. before
use your library i have some question.
Point 1
what was wrong you notice in this routine GetFastestNISTDate(); the routine was query few NIST time servers and get the utctime.
utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
this routine GetFastestNISTDate(); was returning utcDateTime....was not a utc time ?
Point 2
when i was calling GetFastestNISTDate(); routine i notice some time this routine was returning DateTime.MinValue which was not expected result. i could understand why it was happening because NIST time servers was busy or blocked or timeout occured at that time.
Point 3
if i use your current code/library NodaTime.NetworkClock then i like to know which NTP server it will query by default?
if i use NodaTime.NetworkClock then is there any chance that some time i may get wrong date or null date due to NTP server is busy/block or timeout occur?
EDIT 5
var instant = NetworkClock.Instance.Now;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
lbldate.Text = zonedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
lbltime.Text = zonedDateTime.ToString("hh:mm:ss", CultureInfo.InvariantCulture);
Your GetFastestNISTDate function uses the daytime protocol - which is essentially deprecated and NOT meant for machine interaction because its results are in no specific format. Even the docs from NIST strongly encourage users to use NTP instead of daytime.
You can find a simple C# implementation of an NTP client here.
To make things easier, I've implemented this client as a NodaTime.IClock. The code is on GitHub here. Simply install it from NuGet:
Install-Package NodaTime.NetworkClock
Then you can use it just like you would use the SystemClock:
var instant = NetworkClock.Instance.Now;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
You shouldn't be converting the DateTime to a string and back - but your current problem is that you're converting the UTC value you get back from the server into a local DateTime for no obvious reason. Ideally, I'd suggest changing GetFastestNISTDate() to return an Instant, but assuming you can't do that:
Don't do the parsing yourself. Take the appropriate substring from the response, then use DateTime.ParseExact, specifying CultureInfo.InvariantCulture and DateTimeStyles.AssumeUniversal
Don't convert the UTC DateTime to a local version - it's pointless and confusing
Use Instant.FromDateTimeUtc to convert a UTC DateTime to an instant
The final part of your code (the last three lines) is okay, but why do you need a DateTime at all? If you can make as much of your code as possible use Noda Time, you'll get the greatest benefits in terms of code clarity.
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.