Strip seconds from datetime

前端 未结 8 1421
死守一世寂寞
死守一世寂寞 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 05:43

    How about this rather elegant solution?

    new DateTime(DateTime.UtcNow.Ticks / 600000000 * 600000000)
    

    ... which will also strip any milli/micro/nanoseconds.

    0 讨论(0)
  • 2021-01-04 05:46
    DateTime time = DateTime.Now;
    string timestring = time.ToString("g");
    

    ToString("g") will convert DateTime to string and remove seconds.

    Output: 03/29/2018 11:11 PM

    0 讨论(0)
  • 2021-01-04 05:48

    You can create a new instance of date with the seconds set to 0.

    DateTime a = DateTime.UtcNow;
    DateTime b = new DateTime(a.Year, a.Month, a.Day, a.Hour, a.Minute, 0, DateTimeKind.Utc);
    
    Console.WriteLine(a);
    Console.WriteLine(b);
    
    0 讨论(0)
  • 2021-01-04 05:49
    // 2.3 - 0.3 = 2.0
    public static DateTime Floor(this DateTime value, TimeSpan interval) {
        var mod = value.Ticks % interval.Ticks;
        return value.AddTicks( -mod );
    }
    
    // 2.3 - 0.3 + 1 = 3.0
    public static DateTime Ceil(this DateTime value, TimeSpan interval) {
        var mod = value.Ticks % interval.Ticks;
        if (mod != 0) return value.AddTicks( -mod ).Add( interval );
        return value;
    }
    
    0 讨论(0)
  • 2021-01-04 06:00

    You can do

    DateTime dt = DateTime.Now;
    dt = dt.AddSeconds(-dt.Second);
    

    to set the seconds to 0.

    0 讨论(0)
  • 2021-01-04 06:02

    A simple solution which strips both seconds and milliseconds from a DateTime:

    DateTime dt = DateTime.Now;
    DateTime secondsStripped = dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);
    
    0 讨论(0)
提交回复
热议问题