0

I had an issue when assigning DateTime object lets say a :- DateTime object1 = "03/11/2021"; // 3rd November 2021 into another DateTime object DateTime object2 = object1;

Then object2 would become "11/03/2021" automatically. I tried hard creating a new DateTime object and the result still similar. Any help would be appreciated.

Snipshot of the original code Watch

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • 6
    A `DateTime`, internally, is just a count of 100ns intervals since midnight at the start of 01/01/0001. Any formatting you're observing is happen when you *convert it to a string*. Internally it has no format information, and like I say, is just a count. – Damien_The_Unbeliever Nov 03 '21 at 09:20
  • For your information, Datetime is a struct (value type). It clone each allocation. https://stackoverflow.com/questions/4265399/how-can-i-clone-a-datetime-object-in-c `user.CheckinDt = logusr.CheckinDt //clone value` – Tohm Nov 03 '21 at 09:42
  • You can try : `user.CheckinDt.ToString("dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo)` – Tohm Nov 03 '21 at 09:45
  • @Tohm .. The value in my newdt is correct. It is what i stored in the sqlite. But when assign to the user.CheckinDt the ticks it is seeing a different value. I read through the pinned, but did i clone to my user.CheckinDt ?? cause i am assigning `user.CheckinDt = new DateTime(Year,Month,Day)` , can advise what to change there? – Keith Chai Nov 03 '21 at 10:10
  • 1
    Please do not post code or errors as images. Please post a [MCVE] that demonstrates the problem – Jason Nov 03 '21 at 10:19
  • It is obviously not re-creatable with: `var newDt = new DateTime(2021, 11, 3); var checkinDt = new DateTime(newDt.Year, newDt.Month, newDt.Day, newDt.Hour, newDt.Minute, newDt.Second);` So perhaps there is something going on in the `checkinDt` property in the user class? – Magnus Nov 03 '21 at 12:21
  • `sqlLite.SqlLiteDtFormat = "dd/MM/yyyy"` ? – Tohm Nov 04 '21 at 08:33

1 Answers1

2

First of all: DateTime object1 = "03/11/2021"; - you don't have it - it would not compile, as string is not implicitly convertible to DateTime.

Secondly: DateTime is nothing more than just a numeric representation of time. So under the hood it is nothing more than just a number (as mentioned, number of ns since a given point in time). How the date is displayed is just a minor concern - value under the hood remains the same.

Please read on how to format date in C# and how to parse it.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • Please see my screenshot. My question is not my actual code. It just for explaining. I am not assigning 03/11/2021 to my datetime. I am pretty sure the object i am passing in is not stored properly. – Keith Chai Nov 03 '21 at 09:29