1

I want to store the time in a SQL Server database without seconds or milliseconds, eg 15:42:00instead of 15:42:05.009. However, it is stored in seconds and milliseconds. How can I remove seconds and milliseconds with getter and setter?

This is my code:

[Column(TypeName = "time")]
[DisplayFormat(DataFormatString = @"{0:hh\:mm}")]
public TimeSpan Time { get; set; }

enter image description here

CLARIFICATION: Through the frontend, I enter a value in the 12-hour time unit into the input, for example "12:30 ". I want to save the value coming from the frontend to the database in the same form. However, it is stored in the database with seconds and milliseconds, for example "12:30:24.0170000". I want to save the incoming value to the database without seconds and milliseconds.

P.S. That's right, I can change the display format of the same value in the database in the frontend. But I want to do everything in the backend.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • 2
    The date-related database types, including `time` have no format, they're binary types. Same with `DateTime` and `TimeSpan`. If you want to eliminate seconds from storage you'll have to do so while storing the data. If you want to display time without seconds and milliseconds the `DisplayFormat` should be enough. – Panagiotis Kanavos Dec 21 '22 at 10:10
  • Does this answer your question? https://stackoverflow.com/questions/1004698/how-to-truncate-milliseconds-off-of-a-net-datetime?rq=1 – NineBerry Dec 21 '22 at 10:16
  • 2
    You can use `time(0)` to eliminate milliseconds but not seconds. If you want to store times without seconds using EF Core you'll have to modify the value in the property setter. `TimeSpan` is immutable so you'll have to create a new value. Create a `TimeSpan` field, eg `TimeSpan _time` and create a setter that stores a value without the seconds, eg `set { _time=new TimeSpan(value.Hours, value.Minutes,0);}`. You'll have to decide what to do with rounding though – Panagiotis Kanavos Dec 21 '22 at 10:17
  • you could use the `TotalMinutes` and truncate the decimal part by a cast to `int` [like this](https://dotnetfiddle.net/BV4cbU), but that would simply drop them at all, there is no rounding. – Mong Zhu Dec 21 '22 at 10:18
  • After searching some tutorials, I found a solution to my question above. According to this, with the `public DateTime Time { get; set; }` field, I can use the DateTime class's built-in function **ToShortTimeString()**. – Zohidbek Mengliboyev Jan 05 '23 at 04:25

0 Answers0