How to remove time portion of date in C# in DateTime object only?

C#Datetime

C# Problem Overview


I need to remove time portion of date time or probably have the date in following format in object form not in the form of string.

06/26/2009 00:00:00:000

I can not use any string conversion methods as I need the date in object form.

I tried first converting the DateTime to a string, remove the time specific date from it, but it adds 12:00:00 AM as soon as I convert it back to DateTime object back again.

C# Solutions


Solution 1 - C#

Use the Date property:

var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;

The date variable will contain the date, the time part will be 00:00:00.

Solution 2 - C#

You can use format strings to give the output string the format you like.

DateTime dateAndTime = DateTime.Now;
Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011

Read more about Custom date and time format strings.

Solution 3 - C#

Use the method ToShortDateString. See the documentation http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx

var dateTimeNow = DateTime.Now; // Return 00/00/0000 00:00:00
var dateOnlyString = dateTimeNow.ToShortDateString(); //Return 00/00/0000

Solution 4 - C#

Have a look at the DateTime.Date property.

> Gets the date component of this instance.

Solution 5 - C#

The Date property will return the date at midnight.

One option could be to get the individual values (day/month/year) separately and store it in the type you want.

var dateAndTime = DateTime.Now; 
int year = dateAndTime.Year;
int month = dateAndTime.Month;
int day = dateAndTime.Day;

string.Format("{0}/{1}/{2}", month, day, year);

Solution 6 - C#

None of the above answers solved my problem on winforms.

the easiest way to reach ONLY date is the simple function in Datetime:

DateTime dt = DateTime.now;
String BirthDate = dt.ToShortDateString();

You will only have date in Birthday string .

Solution 7 - C#

Try to make your own Structure for that. DateTime object will have date and time both

Solution 8 - C#

You can't. A DateTime in .NET always have a time, defaulting to 00:00:00:000. The Date property of a DateTime is also a DateTime (!), thus having a time defaulting to 00:00:00:000 as well.

This is a shortage in the .NET Framework, and it could be argued that DateTime in .NET violates the Single Responsibility Principle.

Solution 9 - C#

The easiest way is something like this and it will return only the date:

var date = DateTime.Now.ToShortDateString();

Solution 10 - C#

DateTime.Date

var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime

Solution 11 - C#

Here is another method using String.Format

    DateTime todaysDate = DateTime.UtcNow;

    string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);

    Console.WriteLine("Date with Time: "+ todaysDate.ToString());

    Console.WriteLine("Date Only : " + dateString);

Output:

Date with Time: 9/4/2016 11:42:16 AM

Date Only : 04/09/2016

This also works if the Date Time is stored in database.

For More Date and Time formatting check these links:

Reference 1

Reference 2

Hope helps.

Solution 12 - C#

This way of get only date without time

DateTime date = DateTime.Now;
string Strdateonly = date.ToString("d");

Output = 5/16/2015

Solution 13 - C#

I wrote a DateOnly structure. This uses a DateTime under the skin but no time parts are exposed publically:

using System;

public struct DateOnly : IComparable, IFormattable, IComparable<DateOnly>, IEquatable<DateOnly>
{

	private DateTime _dateValue;

	public int CompareTo(object obj)
	{
		if (obj == null)
		{
			return 1;
		}

		DateOnly otherDateOnly = (DateOnly)obj;
		if (otherDateOnly != null)
		{
			return ToDateTime().CompareTo(otherDateOnly.ToDateTime());
		}
		else
		{
			throw new ArgumentException("Object is not a DateOnly");
		}
	}

	int IComparable<DateOnly>.CompareTo(DateOnly other)
	{
		return this.CompareToOfT(other);
	}
	public int CompareToOfT(DateOnly other)
	{
		// If other is not a valid object reference, this instance is greater.
		if (other == new DateOnly())
		{
			return 1;
		}
		return this.ToDateTime().CompareTo(other.ToDateTime());
	}

	bool IEquatable<DateOnly>.Equals(DateOnly other)
	{
		return this.EqualsOfT(other);
	}
	public bool EqualsOfT(DateOnly other)
	{
		if (other == new DateOnly())
		{
			return false;
		}

		if (this.Year == other.Year && this.Month == other.Month && this.Day == other.Day)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public static DateOnly Now()
	{
		return new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
	}

	public static bool TryParse(string s, ref DateOnly result)
	{
		DateTime dateValue = default(DateTime);
		if (DateTime.TryParse(s, out dateValue))
		{
			result = new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
			return true;
		}
		else
		{
			return false;
		}
	}

	public static DateOnly Parse(string s)
	{
		DateTime dateValue = default(DateTime);
		dateValue = DateTime.Parse(s);
		return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
	}

	public static DateOnly ParseExact(string s, string format)
	{
		CultureInfo provider = CultureInfo.InvariantCulture;
		DateTime dateValue = default(DateTime);
		dateValue = DateTime.ParseExact(s, format, provider);
		return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
	}

	public DateOnly(int yearValue, int monthValue, int dayValue) : this()
	{
		Year = yearValue;
		Month = monthValue;
		Day = dayValue;
	}

	public DateOnly AddDays(double value)
	{
		DateTime d = new DateTime(this.Year, this.Month, this.Day);
		d = d.AddDays(value);
		return new DateOnly(d.Year, d.Month, d.Day);
	}

	public DateOnly AddMonths(int months)
	{
		DateTime d = new DateTime(this.Year, this.Month, this.Day);
		d = d.AddMonths(months);
		return new DateOnly(d.Year, d.Month, d.Day);
	}

	public DateOnly AddYears(int years)
	{
		DateTime d = new DateTime(this.Year, this.Month, this.Day);
		d = d.AddYears(years);
		return new DateOnly(d.Year, d.Month, d.Day);
	}

	public DayOfWeek DayOfWeek
	{
		get
		{
			return _dateValue.DayOfWeek;
		}
	}

	public DateTime ToDateTime()
	{
		return _dateValue;
	}

	public int Year
	{
		get
		{
			return _dateValue.Year;
		}
		set
		{
			_dateValue = new DateTime(value, Month, Day);
		}
	}

	public int Month
	{
		get
		{
			return _dateValue.Month;
		}
		set
		{
			_dateValue = new DateTime(Year, value, Day);
		}
	}

	public int Day
	{
		get
		{
			return _dateValue.Day;
		}
		set
		{
			_dateValue = new DateTime(Year, Month, value);
		}
	}

	public static bool operator == (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() == aDateOnly2.ToDateTime());
	}

	public static bool operator != (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() != aDateOnly2.ToDateTime());
	}

	public static bool operator > (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() > aDateOnly2.ToDateTime());
	}

	public static bool operator < (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() < aDateOnly2.ToDateTime());
	}

	public static bool operator >= (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() >= aDateOnly2.ToDateTime());
	}

	public static bool operator <= (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() <= aDateOnly2.ToDateTime());
	}

	public static TimeSpan operator - (DateOnly aDateOnly1, DateOnly aDateOnly2)
	{
		return (aDateOnly1.ToDateTime() - aDateOnly2.ToDateTime());
	}


	public override string ToString()
	{
		return _dateValue.ToShortDateString();
	}

	public string ToString(string format)
	{
		return _dateValue.ToString(format);
	}

	public string ToString(string fmt, IFormatProvider provider)
	{
		return string.Format("{0:" + fmt + "}", _dateValue);
	}

	public string ToShortDateString()
	{
		return _dateValue.ToShortDateString();
	}

	public string ToDbFormat()
	{
		return string.Format("{0:yyyy-MM-dd}", _dateValue);
	}
}

This is converted from VB.NET, so apologies if some conversions are not 100%

Solution 14 - C#

I'm surprised no one has mentioned DateTime.Today

var date = DateTime.Today;
// {7/1/2014 12:00:00 AM}

See MSDN

Solution 15 - C#

Use date.ToShortDateString() to get the date without the time component

var date = DateTime.Now
var shortDate = date.ToShortDateString() //will give you 16/01/2019

use date.ToString() to customize the format of the date

var date = DateTime.Now
var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019

Solution 16 - C#

If you are converting it to string, you can easily do it like this.

I'm taking date as your DateTime object.

date.ToString("d");

This will give you only the date.

Solution 17 - C#

You Can Try This for the Only Date From the Datetime

String.Format("{0:d/M/YYYY}",dt);

Where dt is the DateTime

Solution 18 - C#

Came across this post when trying to solve the original Q.

I am using Asp.Net and after some research I have found when you are binding to the value of the date in code behind, you can drop the time so it will not display on screen.

C#:

DateTime Today = DateTime.Now;

aspx:

<%: this.Today.ToShortDateString() %>

Solution 19 - C#

use

DateTime.Now.ToString("dd-MM-yyyy");

Solution 20 - C#

You can use this simple code below.

Code: DateTime.Now.ToShortDateString();

Ex. Console.WriteLine(DateTime.Now.ToShortDateString());

Solution 21 - C#

Since .NET 6 / C# 10 you can do this:

var dateOnly = DateOnly.FromDateTime(dateTime);

Solution 22 - C#

in my experience none of the said solutions worked, maybe because I wanted to remove the time from extracted date from database, but the code below worked fine:

var date = target_date.Value.ToString("dd/MM/yyyy"); 

Solution 23 - C#

string dt = myCalender.SelectedDate.ToString();
string date = dt.Remove(10);
displayDate.Content = date;

If you take date from calender, with this we also get time. Which is not required all time. Using this we can remove time from date.

Solution 24 - C#

Declare the variable as a string.

example :

public string dateOfBirth ;

then assign a value like :

dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();

Solution 25 - C#

Create a struct that holds only the properties you want. Then an extension method to easily get that struct from an instance of DateTime.

public struct DateOnly
{
    public int Day { get; set; }
    public int Month { get; set; }
    public int Year { get; set; }
}

public static class DateOnlyExtensions
{
    public static DateOnly GetDateOnly(this DateTime dt)
    {
        return new DateOnly
        {
            Day = dt.Day,
            Month = dt.Month,
            Year = dt.Year
        };
    }
}

Usage

DateTime dt = DateTime.Now;
DateOnly result = dt.GetDateOnly();

Solution 26 - C#

I know this is an old post with many answers, but I haven't seen this way of removing the time portion. Suppose you have a DateTime variable called myDate, with the date with time part. You can create a new DateTime object from it, without the time part, using this constructor:

public DateTime(int year, int month, int day);

Like this:

myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);

This way you create a new DateTime object based on the old one, with 00:00:00 as time part.

Solution 27 - C#

This could be simply done this way:

var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)

Solution 28 - C#

To get only the date portion use the ToString() method,

example: DateTime.Now.Date.ToString("dd/MM/yyyy")

Note: The mm in the dd/MM/yyyy format must be capitalized

Solution 29 - C#

Use .Date of a DateTime object will ignore the time portion.

Here is code:

DateTime dateA = DateTime.Now;
DateTime dateB = DateTime.Now.AddHours(1).AddMinutes(10).AddSeconds(14);
Console.WriteLine("Date A: {0}",dateA.ToString("o"));
Console.WriteLine("Date B: {0}", dateB.ToString("o"));
Console.WriteLine(String.Format("Comparing objects A==B? {0}", dateA.Equals(dateB)));
Console.WriteLine(String.Format("Comparing ONLY Date property A==B? {0}", dateA.Date.Equals(dateB.Date)));
Console.ReadLine();

Output:

>Date A: 2014-09-04T07:53:14.6404013+02:00
>Date B: 2014-09-04T09:03:28.6414014+02:00
>Comparing objects A==B? False
>Comparing ONLY Date property A==B? True

Solution 30 - C#

Use a bit of RegEx:

Regex.Match(Date.Now.ToString(), @"^.*?(?= )");

Produces a date in the format: dd/mm/yyyy

Solution 31 - C#

For using by datalist, repeater.. in aspx page:<%# Eval("YourDateString").ToString().Remove(10) %>

Solution 32 - C#

static void Main(string[] args)
{
    string dateStrings =  "2014-09-01T03:00:00+00:00" ;
   
    DateTime convertedDate = DateTime.Parse(dateStrings);
    Console.WriteLine("  {0} ----------------- {1}",
                      
    convertedDate,DateTime.Parse(convertedDate.ToString()).ToString("dd/MM/yyyy"));
     
    Console.Read();
}

Solution 33 - C#

This code gives you a clear view of writing Date as well as Time separately

string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00");
        string date = DateTime.Now.ToString("M-dd-yyyy");
        MessageBox.Show(date + "\n" + time);

Hope this helps.

Solution 34 - C#

Getting the Date part of a DateTime object didn't workout for me because I'm working on the client-side and the returned web service values have some null dates. As a result, it tries to get the Date part of a null value and it throws a runtime exception. The following example is how I solved my problem:

string dt = employer.BirthDay.ToString();
if(dt == ""){ dt = "N/A";}
else dt = dt.Substring(0,10);
  1. Get the DateTime value as string into a string variable.
  2. Check if it's null. If null, assign a string variable.
  3. If not null, get the first 10 characters of the string DateTime value and assign it to the string variable.

I'm sharing this for future reference.

Solution 35 - C#

Try this, if you use a DateTimeOffset, it will also take care of the timezone

date1 = date1.LocalDateTime.Date;

If you need to add hours, use this:

date1 = date1.LocalDateTime.Date;
date1 = date1.AddHours(23).AddMinutes(59).AddSeconds(59);

Solution 36 - C#

Add Date property to the DateTime variable

var dateTime = DateTime.Now
var onlyDate = dateTime.Date

Or You can use DataType annotation as well.

[DataType(DataType.Date)]
public DateTime dateTime {get; set;}

The DataType annotation is inside the System.ComponentModel.DataAnnotations namespace.

Solution 37 - C#

DateTime dd=DateTiem.Now;
string date=dd.toString("dd/MM/YYYY");

Solution 38 - C#

If you want to remove part of time from a DateTime, try using this code:

DateTime dt = new DateTime();

dt = DateTime.Now; //ex: 31/1/2017 6:30:20 PM

TimeSpan remainingTime = new TimeSpan(0, dt.Hour - 5, dt.Minute - 29, dt.Second - 19);
dt=dt.Add(remainingTime);

label1.Text = dt.ToString("HH:mm:ss"); // must be HH not hh

the output : 01:01:01

Solution 39 - C#

Just use one line of code:

var dateAndTime = DateTime.Now.Date;

Solution 40 - C#

I think you would this: DateTime onlyDate = DateTime.Today.Date; or, that's the same DateTime onlyDate = yourDateTime.Date; So use the property Date.

Solution 41 - C#

In case you would want to use Binding and show only Date portion without time

ToolTip="{Binding TransactionModel.TransactionDate, StringFormat=d}"

Solution 42 - C#

You can use a Date library like https://www.nuget.org/packages/Date/ to work with Date values, convert them to and from DateTimes, etc.

Disclaimer I'm the author of the above package.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionim uselessView Question on Stackoverflow
Solution 1 - C#driisView Answer on Stackoverflow
Solution 2 - C#0x49D1View Answer on Stackoverflow
Solution 3 - C#Adriano SilvaView Answer on Stackoverflow
Solution 4 - C#NickView Answer on Stackoverflow
Solution 5 - C#NoviceProgrammerView Answer on Stackoverflow
Solution 6 - C#MehraDView Answer on Stackoverflow
Solution 7 - C#Umesh CHILAKAView Answer on Stackoverflow
Solution 8 - C#Tomas VinterView Answer on Stackoverflow
Solution 9 - C#flkView Answer on Stackoverflow
Solution 10 - C#VikciaRView Answer on Stackoverflow
Solution 11 - C#Shaiju TView Answer on Stackoverflow
Solution 12 - C#Mayank GuptaView Answer on Stackoverflow
Solution 13 - C#Matt WilkoView Answer on Stackoverflow
Solution 14 - C#LukeFView Answer on Stackoverflow
Solution 15 - C#Nathanael MayneView Answer on Stackoverflow
Solution 16 - C#TASView Answer on Stackoverflow
Solution 17 - C#VikasView Answer on Stackoverflow
Solution 18 - C#JohnView Answer on Stackoverflow
Solution 19 - C#JamesView Answer on Stackoverflow
Solution 20 - C#IanView Answer on Stackoverflow
Solution 21 - C#L01NLView Answer on Stackoverflow
Solution 22 - C#DanielView Answer on Stackoverflow
Solution 23 - C#hizbul25View Answer on Stackoverflow
Solution 24 - C#Saud KhanView Answer on Stackoverflow
Solution 25 - C#masonView Answer on Stackoverflow
Solution 26 - C#Guillermo GutiérrezView Answer on Stackoverflow
Solution 27 - C#HichemSeeSharpView Answer on Stackoverflow
Solution 28 - C#nate.pyView Answer on Stackoverflow
Solution 29 - C#JotaView Answer on Stackoverflow
Solution 30 - C#DividedByZeroView Answer on Stackoverflow
Solution 31 - C#Filip DialmView Answer on Stackoverflow
Solution 32 - C#ManiView Answer on Stackoverflow
Solution 33 - C#ZeroView Answer on Stackoverflow
Solution 34 - C#apolloView Answer on Stackoverflow
Solution 35 - C#iwhpView Answer on Stackoverflow
Solution 36 - C#Naveed HematmalView Answer on Stackoverflow
Solution 37 - C#JamesView Answer on Stackoverflow
Solution 38 - C#Na'ilView Answer on Stackoverflow
Solution 39 - C#NinjaCoderView Answer on Stackoverflow
Solution 40 - C#Carmine CheckerView Answer on Stackoverflow
Solution 41 - C#Kovalenko IhorView Answer on Stackoverflow
Solution 42 - C#balintnView Answer on Stackoverflow