DocumentDB Query to find created date - c#

I want to retrieve the documents with only documentID and document Created DateTime details. I am able to get the DocumentID by following query but how can we get the Document created datetime.
select c.id from c
However, along with id I need to get the document created date also
Any help on this appreciated !

I am able to get the DocumentID by following query but how can we get
the Document created datetime.
From this official doc , the automatically generated properties of the document when it is created consists only of the following: _rid,_etag,_ts,_self,id.
_ts represents last updated timestamp of the resource, so if this document has not been updated, then this time is the createTime. You could query it via Select c.id,c._ts from c.
So, maybe you need to log createTime by yourself when you create documents so that you could query the createTime later.
Hope it helps you.
The id , _ts or other custom properties like DocumentReadingCreatedDate are all properties in the document which is not divided into system details or non-system details. Just some of the properties I mentioned above are the fields that cosmosdb will automatically generate for you.
So you just need to use sql : select c._ts from c to find the newest update time of this document. You could get a long type data such as 1520216339 ,then you could convert it into datetime format such as Sun Jan 18 22:16:56 CST 1970 in your program.
If your documents have been updated and you must get the create time of the document, you can't use _ts field. You could only use your custom field DocumentReadingCreatedDate.

The _ts is a Unix Timestamp value.
You need to convert it. The following C# sample will do it.
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime;
}
Or you can create a UFD that you can use in your query, The following is one that will work
function epochToDate (ts) {
return new Date(ts*1000);
}
You would use it as follows:
SELECT * FROM c WHERE udf.epochToDate(c._ts) == ....

Related

DateTime.Date conversion in EF Core Generated Query

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.

Handle time change (summer- and default time) in MongoDB with C# driver

I have a centralized logging service written in C#. This service receives log entries (in JSON string) and add them in a MongoDB collection. I use the official C# MongoDB driver and MongoDB Version 3.0.
Let's say I have a document with this basic structure (and example):
{
"_id" : ObjectId("562c2785a075b738c484ad99"),
"Service" : "WebServer A",
"Description" : "User has logged in",
"SourceTime" : ISODate("2015-10-25T00:41:15.469Z")
}
As you can see in this document I have a date field called "SourceTime". This UTC format doesn't tell me whether the document is created in summer- (+02:00) or in default time (+01:00).
I would like to ask you what's the best way to store a date field with an ISODate object without having problems with summer- and default time?
Is it better to store an ISODate with following format in C#?
{
"SourcTime" : ISODate("2015-10-25T01:41:15.469+01:00")
}
If yes, does anyone has an example how to achieve that with C#?
At the moment, I add a document as follows:
// parse String _document to a BsonDocument
BsonDocument document = BsonDocument.Parse(_document);
// Change SourceTime field to a DateTime object
var TimeElem = document.GetElement("SourceTime").Value.ToString();
DateTime newTime = DateTime.Parse(TimeElem);
// Update document
document.Set("SourceTime", newTime.ToUniversalTime()); // result ISODate("2015-10-25T00:41:15.469Z")
// Add to MongoDB
var collection = _database.GetCollection<BsonDocument>(_collectionName);
collection.InsertOneAsync(document);
Thank you very much for your help. Very appreciate it.
Regards
MongoDB uses a Bson Date which does not store the timezone within the date -
The official BSON specification refers to the BSON Date type as the UTC datetime.
https://docs.mongodb.org/manual/reference/bson-types/#date
The ISODate("2015-10-25T01:41:15.469+01:00") is just a javascript helper method to allow you to convert between an ISODate and a BsonDate so the offset within the string just change converted back to a UTC time.
If you require the timezone or the offset you will need to manually store this within the document, and convert it back after deserialization.

To Get Data that its type is Date in C#

In my SQL database, I have BeginDate column of type date (so I want to get only day,month,year).
I add data into database in C#.
I look at Table_Data and everything is fine (for example BeginDate = 05/04/2014).
But when I get this data from database in C# with
string a= dt.Rows[i]["BeginDate"].ToString()
result is: a= 05/04/2014 12:00:00 AM
Why?
I can remove hour in string a with any methods. But why? I want to get only 05/04/2014 from database.
This is a display problem, not a data problem. Use the Formatting features of DateTime.ToString() to display the date in the format that you want.
If the data is coming out of the database in string form, use DateTime.Parse on it first.
Reference
Standard Date and Time Formats
Custom Date and Time Formats

Subsonic date changing after .Save() is called

I have started using Subsonic for developing a small CMS web application.
I noticed that when ever I call the .Save() method of the Subsonic-Table-Object, that my date field called 'CreatedOn' gets overwritten with today's date.
Subsonic Info: Version 3.0.0.4 using ActiveRecord
// add article from dataset
Article a = new Article();
a.Title = article["title"].ToString();
a.Synopsis = article["teaser"].ToString();
a.Body = article["body"].ToString();
a.Keywords = string.Empty;
a.Photo = string.Empty;
///articles/2010/04/14/deregistration-of-trade-unions
a.CreatedOn = DateTime.Parse(sDestin.Substring(9, 10));
a.UpdatedOn = DateTime.Parse(sDestin.Substring(9, 10));
a.Save();
Before saving, the CreatedOn field is set to the correct date (same as UpdatedOn).
As soon as the .Save() method is run, the CreatedOn field changes to today's date. The UpdatedOn date field maintains the same date that was assigned to it.
What I have tried:
I've double checked the Article table, there are no default values such as (GetDate()) present for any of the date fields.
I've rebuilt my templates several times.
I've also attempted to reset and save the CreatedOn date field a second time.
Any help would be appreciated.
Answer
After further investigation I found the problem.
Subsonic appears to be generating a line of code which is manipulating the date.
I dont know why its doing this only for the CreatedOn date on not the UpdatedOn date. Both fields are identical in structure (MSSQL 2005).
Extracted from the Save() method of my article object.
public void Add(IDataProvider provider){
//this.CreatedOn=CMSDB.DateTimeNowTruncatedDownToSecond(); // commenting this out works, CreatedOn is no longer overwritten
var key=KeyValue();
if(key==null){
var newKey=_repo.Add(this,provider);
this.SetKeyValue(newKey);
}else{
_repo.Add(this,provider);
}
SetIsNew(false);
OnSaved();
}
Here is the anomolous context method Subsonic created:
internal static DateTime DateTimeNowTruncatedDownToSecond() {
var now = DateTime.Now;
return now.AddTicks(-now.Ticks % TimeSpan.TicksPerSecond);
}
Note: Stackoverflow required me to wait 6 hours to post the answer so I placed it here instead.
"CreatedOn" is a convention in SS ActiveRecord - when a field is called "CreatedOn" the code that you see to set the date is added by the T4 templates. It clearly isn't helpful in your case.
Two options:
edit your T4 template to remove the offending line (so you will not be able to take advantage of the auto-time-stamping in any of your model objects)
change the name of the field to something else
If accepted answer is not applicable for you as with my case, you might do a
new InlineQuery().Execute(string query)
to update the said fields.

Getting empty values for "DateComposed" and "timeComposed"

I am trying to read "DateComposed" and "timeComposed" values of Notes Discussion Database using Domino.dll. While reading I am getting "" for both of them.
Sample code:
DateTime DiaryDate = (DateTime)((object[])docJournal.GetItemValue("DateComposed"))[0];
DateTime dtTimeCreated = (DateTime)((object[])docJournal.GetItemValue("timeComposed"))[0];
Is there another way to read them?
Try the document "GetItemValueDateTimeArray" method instead of "GetItemValue"
Actually, the DateComposed and TimeComposed fields are "Computed for Display" fields, meaning these are not actual fields stored on the document, but are computed on the fly when a document is rendered through a form. In looking at the form design of the out-of-the-box Notes Discussion template, I see those two fields are computed based on the document's internal created date. So, take a look at the getCreated method, which returns a DateTime. You can then parse out the date and time values.
Try something like this:
...
Document docJournal = ...
DateTime DiaryDate = docJournal.getCreated().getLocalTime();
...

Categories

Resources