28

I want to strip/remove seconds from a DateTime. Starting with a full Datetime like:

DateTime datetime = DateTime.UtcNow;

I want to strip the seconds using any inbuilt function or regular expression.

Input: 08/02/2015 09:22:45

Expected result: 08/02/2015 09:22:00

Tom Dufall
  • 871
  • 1
  • 10
  • 21
Deependra Singh
  • 441
  • 1
  • 4
  • 10

10 Answers10

61

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, a.Kind);

Console.WriteLine(a);
Console.WriteLine(b);
shashwat
  • 7,851
  • 9
  • 57
  • 90
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
  • 1
    For consistency, I suggest you either use DateTime.Now for creating "a", or add "DateTimeKind.Utc" to the end of the line creating "b". Creating a UTC time without adding the timezone is likely to cause some strange results. – Patrick M Oct 31 '18 at 17:41
  • to complete Patrick comment, use the ctor with DataTimeKind, so DateTime b = new DateTime(a.Year, a.Month, a.Day, a.Hour, a.Minute, 0, DateTimeKind.Utc); as I just edited – EricBDev May 21 '19 at 13:25
  • This does not strip the seconds from the result either. It only sets them to 0. – IOviSpot Dec 26 '21 at 11:14
  • This was safe direct and easy readable journey and got me there. – Honza P. Feb 11 '22 at 15:47
56

You can do

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

to set the seconds to 0.

ChrisC73
  • 1,833
  • 14
  • 14
14

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);
clamchoda
  • 4,411
  • 2
  • 36
  • 74
9

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);
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
6

How about this rather elegant solution?

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

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

blackforest-tom
  • 438
  • 4
  • 8
  • There's an extra 0 there. You mean / 10_000_000. – AlexDev Mar 07 '19 at 21:00
  • The question was about stripping seconds off a DateTime. But you were right about something being wrong. There are 60 seconds in a minute, not 100 ;) I fixed the answer. By the way: you might wanna update your answer too, since its wrong (not stripping off seconds). Also the syntax error (the underscores) aren't too obvious for junior coders. – blackforest-tom Mar 19 '19 at 16:15
  • ok. since I didn't see a 6 I thought you were trying to strip the milliseconds. – AlexDev Mar 20 '19 at 12:05
4

And as an extension, keeps the kind and also trims milliseconds

public static DateTime TrimSeconds(this DateTime a)
{
    return new DateTime(a.Year, a.Month, a.Day, a.Hour, a.Minute, 0, a.Kind);
}
BobbyTables
  • 4,481
  • 1
  • 31
  • 39
  • This does not strip the seconds from the result either. It only sets them to 0. – IOviSpot Dec 26 '21 at 11:15
  • 2
    @wEight And what happens to the zeroes in the original questions sample of the expexted results? I dont think anyone expects them to be "gone" from a DateTime – BobbyTables Dec 27 '21 at 07:57
2
// 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;
}
adiga
  • 34,372
  • 9
  • 61
  • 83
Denis535
  • 3,407
  • 4
  • 25
  • 36
1

To get a local time you can use:

var dt = DateTime.Now;
dt = dt.AddTicks(-(dt.Ticks % (60 * 10_000_000)));
AlexDev
  • 4,049
  • 31
  • 36
0
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

Harun Diluka Heshan
  • 1,155
  • 2
  • 18
  • 30
Pirate
  • 1,167
  • 1
  • 9
  • 19
  • You'd have to parse it back to a DateTime though to be compliant with OP's request to get a DateTime, not a string. –  Sep 08 '19 at 12:28
  • Small correction to this -- ("g") outputs as military time, thus you would not see "03/29/2018 11:11 PM" but instead will get "03/29/2018 23:11" – Jason Roos Aug 25 '22 at 21:31
0

Late to the party but I've always used "Ticks" arithmetic to do these kinds of things. A straightforward way to "truncate" seconds (and any milliseconds) is:

var d1 = DateTime.Now;
var noSeconds = new DateTime(d1.Ticks / TimeSpan.TicksPerMinute * TimeSpan.TicksPerMinute);

Of course I've encapsulated all of it in neat functions:

public static long Round(this long dateTicks, TimeSpan span) {
    long ticks = (dateTicks + (span.Ticks / 2)) / span.Ticks;
    return ticks * span.Ticks;
}
public static long Floor(this long dateTicks, TimeSpan span) {
    long ticks = (dateTicks / span.Ticks);
    return ticks * span.Ticks;
}

You can see there's a Round method which will round upward if the "span" is halfway to the next interval (31 seconds will round up for example, while 30 will round down). To strip a period, just use the Floor method. The following console script will show how to use these:

using System;

public static long Round(this long dateTicks, TimeSpan span) {
    long ticks = (dateTicks + (span.Ticks / 2)) / span.Ticks;
    return ticks * span.Ticks;
}
public static long Floor(this long dateTicks, TimeSpan span) {
    long ticks = (dateTicks / span.Ticks);
    return ticks * span.Ticks;
}
                
DateTime d1 = new DateTime(2022, 03, 31, 08, 30, 31, 235);
DateTime d2 = new DateTime(Floor(d1.Ticks, TimeSpan.FromMinutes(1)));
DateTime d3 = new DateTime(Round(d1.Ticks, TimeSpan.FromMinutes(1)));

Console.WriteLine(d1);
Console.WriteLine(d2);
Console.WriteLine(d3);

Which will result int:

3/31/2022 8:30:31 AM
3/31/2022 8:30:00 AM
3/31/2022 8:31:00 AM

You could also have rounded or floored in any time span: 5 seconds, 30 seconds, half an hour, etc.

With these Tick-based methods I've created a bunch of overloaded extension methods for many "data and time" types. Feel free to use however you wish:

using System;

public static class DateAndTimeExtensions
{
    public static long Round(this long dateTicks, TimeSpan span) {
        long ticks = (dateTicks + (span.Ticks / 2)) / span.Ticks;
        return ticks * span.Ticks;
    }
    public static long Round(this long dateTicks, TimeSpan span, TimeSpan grace) {
        long ticks = (dateTicks + (span.Ticks - grace.Ticks)) / span.Ticks;
        return ticks * span.Ticks;
    }
    public static long Floor(this long dateTicks, TimeSpan span) {
        long ticks = (dateTicks / span.Ticks);
        return ticks * span.Ticks;
    }
    public static long Ceil(this long dateTicks, TimeSpan span) {
        long ticks = (dateTicks + span.Ticks - 1) / span.Ticks;
        return ticks * span.Ticks;
    }

    public static DateTime Round(this DateTime date, TimeSpan span)
        => new DateTime(date.Ticks.Round(span));
    public static DateTime Round(this DateTime date, TimeSpan span, TimeSpan grace)
        => new DateTime(date.Ticks.Round(span, grace));
    public static DateTime Floor(this DateTime date, TimeSpan span)
        => new DateTime(date.Ticks.Floor(span));
    public static DateTime Ceil(this DateTime date, TimeSpan span)
        => new DateTime(date.Ticks.Ceil(span));
    public static DateTimeOffset Round(this DateTimeOffset date, TimeSpan span)
        => new DateTimeOffset(date.Ticks.Round(span), date.Offset);
    public static DateTimeOffset Round(this DateTimeOffset date, TimeSpan span, TimeSpan grace)
        => new DateTimeOffset(date.Ticks.Round(span, grace), date.Offset);
    public static DateTimeOffset Floor(this DateTimeOffset date, TimeSpan span)
        => new DateTimeOffset(date.Ticks.Floor(span), date.Offset);
    public static DateTimeOffset Ceil(this DateTimeOffset date, TimeSpan span)
        => new DateTimeOffset(date.Ticks.Ceil(span), date.Offset);
    public static TimeSpan Round(this TimeSpan time, TimeSpan span)
        => new TimeSpan(time.Ticks.Round(span));
    public static TimeSpan Round(this TimeSpan time, TimeSpan span, TimeSpan grace)
        => new TimeSpan(time.Ticks.Round(span, grace));
    public static TimeSpan Floor(this TimeSpan time, TimeSpan span)
        => new TimeSpan(time.Ticks.Floor(span));
    public static TimeSpan Ceil(this TimeSpan time, TimeSpan span)
        => new TimeSpan(time.Ticks.Ceil(span));
    public static TimeSpan Abs(this TimeSpan time)
        => new TimeSpan(Math.Abs(time.Ticks));
}

Using the above extension methods you can easily truncate or round in any time span you require. Just look at the following examples:

var d = new TimeSpan(3, 20, 31); // 3h20min31s
var roundedAt5Seconds = d.Round(TimeSpan.FromSeconds(5));  // 03:20:30
var roundedAt1Minute = d.Round(TimeSpan.FromMinutes(1));   // 03:21:00
var flooredAt1Minute = d.Floor(TimeSpan.FromMinutes(1));   // 03:20:00
var roundedAtHalfHour = d.Round(TimeSpan.FromMinutes(30)); // 03:30:00
var flooredAtHalfHour = d.Floor(TimeSpan.FromMinutes(30)); // 03:00:00
OwnageIsMagic
  • 1,949
  • 1
  • 16
  • 31
Loudenvier
  • 8,362
  • 6
  • 45
  • 66