I am having an issue with creating a contract from a custom workflow activity. The contract takes it's activeon date from a field in a related entity. The time portion of the date is removed before being set as the activeon date for the contract. This seems to work as expected but the code is creating wonky dates for the contract. Does anyone have any experience with this?
DateTime startDate;
DateTime endDate;
Anh_home home = <<Get record from service>>;
startDate = home.Anh_ActualPossessionDate.GetValueOrDefault().Date;
endDate = startDate.AddYears(contractDuration).Date.AddSeconds(-1);
newContract = new Contract()
{
Title = contractName,
anhwp_Home = home.ToEntityReference(),
CustomerId = home.Anh_CompanyId,
ActiveOn = startDate,
ExpiresOn = endDate,
BillingCustomerId = home.Anh_CompanyId,
BillingStartOn = startDate,
BillingEndOn = endDate,
ContractTemplateId = dataContext.ContractTemplateSet.FirstOrDefault(x => x.Abbreviation == "HWC").ToEntityReference()
};
newContract.Id = service.Create(newContract);
Below is the results of a query on the filtered views. It seems like the activeon date is setting the activeonutc field but my understanding is that CRM handles the conversion to UTC based on the users settings.
Thanks.
So I have stumbled upon the answer to my question on this great blog post https://community.dynamics.com/crm/b/develop1/archive/2011/12/06/dynamics-crm-datetimes-the-last-word.
It seems that when you retrieve data from CRM via the SDK the date is always sent as UTC but you can send data either as local time or UTC. The issue I was having is that I was treating the date retrieved from the other entity as local time when it was really UTC. So when I saved my new contract CRM was correctly taking the UTC time I provided and converting it to local time.
To fix this issue I simply made a call to the .ToLocalTime() method of the DateTime object of the retrieved record.
Related
I have problem. I have MySQL database and I use DATE type for my date column. I want to save date without time only.
In database date is saved like this 06/02/1999 for example.
But when I try to take it with dapper
var test = connection.QueryFirstAsync<string>(#"SELECT BirthDate FROM Students");
Then it returns 06/02/1999 00:00:00
How can I fix that? I want string without that time that shouldn't even be there in first place.
Thank you very much for answers
Simple (maybe naive) solution is this one:
string date = "06/02/1999 00:00:00";
DateTime dateTime = DateTime.Parse(date);
DateOnly dateOnly = DateOnly.FromDateTime(dateTime);
Note: DateOnly applies to .NET 6, .NET 7 Preview 6
We have a project we are working on and we need to query the database for some data for a particular date.
We configured our DB to read and write date as UTC.
When writing the query to get the data, I noticed that the data for a date was not being pulled from the database.
Here is the code:
transactionDate = Convert.ToDateTime("2021-11-10:T10:00:00").ToLocalTime();
var transactions2 = _transactionsRepo.Query()
.Where(transaction => transaction.AccountId == pharmacy.AccountId.Value)
.Where(transaction => transaction.TransactionDate.Date == transactionDate.Date)
.OrderByDescending(transaction => transaction.TransactionDate)
.Skip(numToSkip)
.Take(pageSize);
On investigation, I noticed that when pulling the data, the DB returns the date as UTC as it should and the date is compared to the input date. But no data is returned. I checked the query generated and noticed this:
DECLARE #__transactionDate_1 datetime = '2021-11-10T10:00:00.000';
DECLARE #__p_2 int = 0;
DECLARE #__p_3 int = 10;
SELECT *
FROM [WalletTransactions] AS [w]
WHERE ([w].[AccountId] = #__AccountId_Value_0) AND (CONVERT(date, [w].[TransactionDate]) = #__transactionDate_1)
ORDER BY [w].[TransactionDate] DESC
OFFSET #__p_2 ROWS FETCH NEXT #__p_3 ROWS ONLY
From the above, the query generated shows that the TransactionDate is converted to just Date and compared to the input date #__transactionDate_1 which is in DateTime form.
Any help on how to solve this will be deeply appreciated.
For anyone facing the same issue, here is a link to the resolution on EF core repo on github:
https://github.com/dotnet/efcore/issues/28380
The issue was caused by a custom value converter that saves and reads all date as UTC.
This means a double conversion was happening and skewing the date time.
Solution is to specify that the input date is in UTC and hence should not be converted.
I am uploading data into BigQuery Cloud by my c# Application. I have column in BigQuery table 'ForDate' with datatype 'Date'.
But in c# datatype is 'datetime'(As date datatype not supported in c#)
I am getting Below error on uploading data to bigquery:
{Invalid date: '2017-01-02T00:00:00' Field: ForDate; Value: 2017-01-02T00:00:00}
What could be the workaround to upload date with date part only and ignore time part from it?
This is working for me:
string currentdatetime = DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
From:
How can I format DateTime to web UTC format?
Import said column as a string, parse in BigQuery to a timestamp value later.
SELECT TIMESTAMP('2017-01-02T00:00:00')
The date field in the BigQuery schema should be marked as a TimeStamp not as a DateTime field. Then you can simply insert the row with:
bqr.Add(attribute, date.ToUniversalTime());
I know its been a while since this question was asked, but for me none of the answers was correct. It seems that the BigQuery NuGet doesn't like date times with specified kind (e.g UTC), and ToUniversalTime() produces an UTC kind.
The only trick that worked for me was to create a new instance of DateTime with none (Unspecified) kind.
var now = DateTime.UtcNow;
var dt = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond);
You can use:
BigQueryDateTimeExtensions.AsBigQueryDate(DateTime.UtcNow)
From: Class BigQueryDateTimeExtensions
For DateTime use:
DateTime.UtcNow.ToString("s")
I have a windows service that runs every night between 3am and 5am. When the job runs the following happens:
var endDate = DateTime.Today.ToUniversalTime(); // Set to midnight
var startDate = endDate.AddDays(-1);
The query that runs at night says something like (All dates are currently stored as UTC):
SELECT * FROM Table WHERE CreatedAt BETWEEN startDate AND endDate
This works just fine, it basically grabs all the data from the previous day when the job runs. I am now developing a UI part to this where a user clicks a button to see the data count that will be processed at night.
The problem I am running into is when a user is at work during normal business hours and clicks that button the counts will be off by 1 day. The count will only display correctly if the local time is after 8pm EST (server is located on the east coast) since that will be after midnight in UTC time.
I tried to solve this with something like:
var now = DateTime.Now;
var midnight = DateTime.Today.ToUniversalTime();
var endDate = (now.Day == midnight.Day) ? midnight.AddDays(1) : midnight;
var startDate = endDate.AddDays(-1);
But this is incorrect as it will only work during some parts of the day. If the button is clicked after midnight local time it would be off by one day again.
Is there any clever way to use the DateTime object to solve this problem?
You can translate the local time to UTC in your UI; or just use DateTime.UtcNow. You have to be careful with ToUniversalTime as it only works if the DateTime you call it on has Kind==DateTimeKind.Local:
var localTimeUtc = TimeZoneInfo.ConvertTimeToUtc(
DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local));
//or (much easier)
var localTimeUtc = DateTime.UtcNow;
And then:
var utcMidnight = localTimeUtc.Date;
var yesterdayUtcMidnight = midnight.AddDays(-1);
now utcMidnight and yesterdayUtcMidnight will cover all of 'yesterday' in UTC time.
On a second note - is your windows service meant to process data from yesterday UTC or yesterday local? If the times in the database are UTC, then your service code should work - but if they've gone in as local time (perhaps with a default GetDate()?) then your code for processing won't work.
I've looked and looked and can't seem to come up with the perfect solution. So, since stack overflow is perfect, this will cure my problem.
I'm getting System.String datetimes from a server (Microsoft CRM if you care). They're in SQL format ("2010-07-23T17:14:40-04:00"). I want to read that in as a .net System.DateTime type with the timezone information preserved, then convert it to local time. This process happens in various timezones, and I'm having trouble staying in synch. Basically, I get lots of CRM records from CRM server (which seems to stamp all the timezones with this Brazilian time (-4)), and I want to write down in my config file the latest one I saw (so I don't go back and pick up values that I already have). I would like to write it down in local time, though. Here's a distillation
I want to take the string "2010-07-23T17:14:40-04:00" and, run some code:
System.Datetime Get_Local_DT(string val);
that will return "2010-07-23 15:14:40" in Central time (-6) and "2010-07-23 16:14:40" in Eastern Time (-5). Let me know what you think.
The reason your times are stamped with the Brazilian time is that is the timezone attached to the user performing the query. CRM stores universal in the database and the filtered views generate that string based on the current user. This way whenever you open up a record in CRM you get a date with a time for your timezone.
If all you are doing is saving the date/time so you can check against it later, I agree with storing as UTC and doing UTC comparisons.
Note that if you're using any ToLocalTime methods, you are showing Local Time on the server and NOT the actual users local time (unless they're in the same timezone as the server). I guess how important this is to you depends on how many timezones you support (1 or many) and where your server is located.
???
private DateTime Get_Local_DT(string strTimestamp, int iUTCOffset)
{
DateTime _dt = DateTime.MinValue;
try
{
DateTime dt = DateTime.Parse(strTimestamp);
DateTime _returnDateTime = dt.ToUniversalTime().AddHours(iUTCOffset);
return _returnDateTime;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return _dt;
}
I think you should use the System.DateTimeOffset type which solves your issue.
String d = "2010-07-23T17:14:40-04:00";
DateTimeOffset dt = DateTimeOffset.Parse(d);
Console.WriteLine(dt.LocalDateTime + " " + dt.ToOffset(TimeSpan.FromHours(-2)));
You could parse the string into a DateTime object using
string sqlDate = "2010-07-23T17:14:40-04:00";
DateTime dt = DateTime.Parse(sqlDate);
Next, you could use the following statement to format it:
dt.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
I tried this code:
void Main()
{
string sqlDate = "2010-07-23T17:14:40-04:00";
DateTime dt = DateTime.Parse(sqlDate);
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo));
}
Output: 2010-07-24 02:44:40
I am in IST. I hope this helps.
Save them as universal time:
DateTime t = DateTime.Parse(str);
t.ToUniversalTime(); // save this
Then show saved time as local:
DateTime t = DateTime.Parse(str);
t.ToLocalTime(); // show this
Always work with universal time, think about local as just a view in mvc.