SRA
SRA

Reputation: 1691

c# DateTime, Trim without converting to string

How can I "trim" a value of a DateTime property in c#?

For example, when I get a date it is of the format "10/1/2010 00:00:00".

How can I "trim" 'Time' 00:00:00 without converting this to a String?

Since I use a property of type DateTime to manipulate this, I don't need to convert to String.

Any help is appreciated.

Upvotes: 3

Views: 3988

Answers (6)

x77
x77

Reputation: 737

You can Trim a Date to Hours Minutes, Day ..

 DateTime t = DateTime.Now;
 DateTime t2 = t - new TimeSpan(t.Ticks % TimeSpan.TicksPerDay);

You can use also TicksPerHour, TicksPerMinute and TicksPerSecond.

Upvotes: 1

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31743

As mentioned by some others

var now = DateTime.Now;
var today = now.Date;

is the preffered way. However, since I like the timtowtdi philosophi:

var now = DateTime.Now;
var today = now.Add(-now.TimeOfDay);

Upvotes: 0

Kevin Gale
Kevin Gale

Reputation: 4458

This can't be done. A DateTime always has a time even if the time is 00:00:00

You can only remove that when converting to a string.

Upvotes: 0

dotalchemy
dotalchemy

Reputation: 2467

Can't you just take it from the DateTime object and then .ToString() it?

DateTime current = DateTime.Now;
string myTime = current.TimeOfDay.Tostring()

You might want to strip the milliseconds from the end...

Upvotes: 0

Brad
Brad

Reputation: 15577

If you are asking if the DateTime object can be time-ignorant, the answer is no. You could create a user-defiened class of Date that just returns the Date portion of a DateTime object. If you are just looking to truncate the time, see below.

DateTime now = DateTime.Now;
DateTime today = now.Date;

or

DateTime now = DateTime.Now;
DateTime today = new DateTime(now.Year, now.Month, now.Day);

Upvotes: 2

codekaizen
codekaizen

Reputation: 27429

var dt = DateTime.Now;    // 10/1/2010 10:44:24 AM
var dateOnly = dt.Date;   // 10/1/2010 12:00:00 AM

Upvotes: 8

Related Questions