0

I am trying to query a collection by date only to check if a corresponding record exist. I have tried a number of solution here and google searches but no success. How can i also save date and time to local time.

Sample Collection

{
    "_id" : ObjectId("5a4f8026762caf03f0a22114"),
    "AttnDate" : ISODate("2018-01-04T20:00:00.000Z"),
    "AllAttendances" : [ 
        {
            "FullName" : "MYDOMAIN\\Michelle",
            "Logged" : ISODate("2018-01-05T13:39:35.338Z"),
            "IdleTime" : 17
        }
    ]
}

Attendance Class

public class Attendance
    {
        [JsonConverter(typeof(ObjectIdConverter))]
        public ObjectId Id { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime AttnDate { get; set; }
        public IEnumerable<TimeRecord> AllAttendances { get; set; }
    }

The Query method

public Attendance FindAttendanceByDate(DateTime CurrentDate)
        {
            var filter = Builders<Attendance>.Filter.Eq(x => x.AttnDate, CurrentDate);
            return context.Attendances.Find(filter).FirstOrDefault();
        }

How i am passing the CurrentDate on the above method

_AttendancesRepositories.FindAttendanceByDate(DateTime.Today);

Solution

In my case, i had to disable "Set time automatically" and "Set time zone automatically" in windows setting to get this to work. I dont know why. I may help someone to save 12 hours of their life.

9
  • You cant save datetime in local timezone unless you use string types. While running queries you can provide the timezone to interpret the datetime in local time zone in 3.6 version.This might help. Commented Jan 5, 2018 at 14:13
  • @Veeram var start = CurrentDate; var ending = CurrentDate.AddDays(1); var filterbuilder = Builders<Attendance>.Filter; var fil = filterbuilder.Gte(x => x.AttnDate, start) & filterbuilder.Lt(x => x.AttnDate, ending); return context.Attendances.Find(fil).FirstOrDefault(); the method is still returning null. Commented Jan 5, 2018 at 14:18
  • Does it work when you pass date like ? var start = new DateTime("2018-01-05"); var ending = new DateTime("2018-01-06"); The idea is to not include the time part or set to all zeros. Commented Jan 5, 2018 at 14:24
  • @Veeram It does not work Commented Jan 5, 2018 at 14:41
  • Can I see your code where you create a date object and document that you are expecting your query to return ? Commented Jan 5, 2018 at 14:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.