Why updating DateTime in MongoDB getting wrong value? - mongodb

I have one model with DateUpdated DateTime property.
Before i update that model, my model information's are
After i update my model information's are
Why MongoDB store wrong DateUpdated value? I tried several times with debugger, and looks like every time that value is changed but with wrong DateTime.
Im using C# Driver.
My Update function is
var query = Query.EQ("_id", p.UserID);
var update = MongoDB.Driver.Builders.Update.Replace(p);
SafeModeResult success = MongoRepository.Profiles().Update(query, update);
SafeModeResult is always success.
My DateUpdated Bson property is
[BsonElement("da")]
[BsonDateTimeOptions(Representation = BsonType.Document)]
public DateTime DateUpdated{ get; set; }

MongoDB stores DateTime values in UTC. What you are seeing is the conversion of local time to UTC.
The best way to handle timezones is to keep all your data in UTC (including in your data model, not just the database) and only convert to local time at the point you display a value to the user.

Related

how do I save and retrieve date in Timestamp format in couchbase databse using springboot

I want to save date in Timestamp format in couchbase database using spring boot application.
I have tried this but getting exception while retrieving date from couchbase.
Here is my code:
POJO:
public class Request {
private Timestamp createDate;
private Timestamp updateDate;
}
Taken in POJO.
saving into db:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
urxRequest.setCreateDate(timestamp);
here it is saving date as a long so while retrieving I am getting cast exception.. can not cast from long to Date..
Please help me for this.

Criteria API order by time between two LocalDateTime

Given an entity with two date fields of type LocalDateTime:
class MyEntity {
private LocalDateTime start;
private LocalDateTime lastUpdate;
}
I want to write a query with criteria api that orders the result set by the time between these two dates.
/* ... */
Root<MyEntity> root = query.from(MyEntity.class);
Order order = ???
root.orderBy(cb.desc(order));
/* ... */
My ideas so far:
CriteriaBuilder#diff wants its arguments to be derived from Number, which LocalDateTime doesn't
CriteriaBuilder#treat maybe treat it as a Timestamp somehow? It is stored as timestamp in the database after all
p.s.:
using EclipseLink 2.7.3
looking for a solution that is not tied to a specific database
Your idea of cb.treat(..) that would do a downcast would not work because Number does not extend/inherit LocalDateTime. And even if it would be possible there would then be a problem because there would not be a way to cast database timestamp type to any Number either directly in database side.
I found this question which might help you. Accepted answer makes use of standard(?) SQL function TIMESTAMPDIFF and that should be quite implementation independent solution. You could make some generic sort based on that answer.
However, one option would also be adding a new calculated field for duration / interval like:
private Duration duration;
#PrePersist // update on each persist
private void calcDuration() {
duration = Duration.between(start, lastUpdate);
}
Then ordering would be like:
Path<Long> duration = root.get("duration"); // duration is stored as bigint or like
criteriaQuery.orderBy(criteriaBuilder.desc(duration)); // or .asc(..)
Naturally duration consumes extra space in db - and it should normally be just transient and/or calculated value - but it might also bring some performance boost.

EF - Save datetime with specific timezone in DB but read it as UTC

Is there a mapping configuration in Entity Framework where I can state to convert any datetime that i will be saving in the db to a specific timezone (eg CEST) and whenever I read it from DB, it should be converted to UTC?
Quick answer: No.
EF just moves the values back and forth.
Suggestion: just store UTC values in the database. If you need to recover the original timezone then store the original timezone as well (but note the common timezone abbreviations are often ambiguous).
Dates and times are hard to process in general, but most systems simply assume a single locale and ignore the issues.
If you have to save datetime in a local zone, you can add a new property in your entity class for the UTC datetime. e.g.
public class MyEntity {
public DateTime LocalDateTime {get; set;}
//use this property in code instead of LocalDateTime.
[NoMapped]
public DateTime UtcDateTime {
get { return /*convert LocalDateTime value to UTC */ }
set { LocalDateTime = /*convert value to local zone */ }
}
}
BTW, I didn't test this method. Just for your reference.

Why does DateTime need to be a byte[] in Entity Framework? And How to I set it ?

I have a DBContext with a DateTime (in the db) that has been defined as a byte[] in the EF. So How do I send a byte[] that representing the current date??
The time should not come across as a byte array datatype. If you're using SQL Server, it's possible you declared your datatype as timestamp instead of datetime, as it shows up as a byte array in code. The timestamp type has been renamed to rowversion in more recent versions of SQL Server to be a bit more clear, as it doesn't hold any type of time data.

Problem with ConcurrencyCheck attribute approach in EF

I've found two ways of concurrency checking for my entities in EF 4.1:
TimeStamp attribute for byte array
ConcurrencyCheck attribute for another types
The first one is very simple. You just mark byte array property as TimeStamp, create additional column in database and voila...
I've got a problem with the second method. Enity Framework has started generate sql script for concurrency check, when I marked the LastUpdateDate property.
Property:
[ConcurrencyCheck]
public DateTime LastUpdateDate { get; set; }
Sql:
select
...
where (([Id] = #3) and ([LastUpdateDate] = #4))
...
#4='value'
But EF does not generate sql script for updating the value of LastUpdateDate?
Is it possible to say EF to update the LastUpdateDate after concurrency checking without triggers or something like this?
And the second question:
What is the best practice of using concurrency checking in EF when you have something like LastUpdateDate property(property will be displayed in UI)? Is it better to check concurency using LastUpdateDate and avoid creating of addtional column for TimeStamp in your tables or
create additional TimeStamp property and renounce of the using DateTime property for concurrency checking?
Have you tried to use a rowversion (timestamp) instead of the DateTime datatype to check for concurency?
I would use the timestamp, because you are sure that the system will update it for you. Further more the value will be very precice.
The following blog posts will give you more information about how to map a timestamp.
The first one shows how to use the timestamp as a concurrency check.
Code First Optimistic Concurrency with Fluent Assertions
Round tripping a timestamp field with EF4.1 Code First and MVC 3