Strip seconds from datetime

前端 未结 8 1422
死守一世寂寞
死守一世寂寞 2021-01-04 05:41

I want to trip/remove seconds from date time. I checked some solution but showing solution using format string like

DateTime datetime = DateTime.UtcNow;


        
相关标签:
8条回答
  • 2021-01-04 06:07

    To get a local time you can use:

    var dt = DateTime.Now;
    dt = dt.AddTicks(-(dt.Ticks % (60 * 10_000_000)));
    
    0 讨论(0)
  • 2021-01-04 06:08

    DateTime is actually stored separately as a Date and a TimeOfDay. We can easily re-initialize the date without including the seconds in the TimeSpan initialization. This also ensures any leftover milliseconds are removed.

    date = date.Date + new TimeSpan(date.TimeOfDay.Hours, date.TimeOfDay.Minutes, 0);
    
    0 讨论(0)
提交回复
热议问题