Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何仅在DateTime对象中删除C#中日期的时间部分?_C#_Datetime - Fatal编程技术网

如何仅在DateTime对象中删除C#中日期的时间部分?

如何仅在DateTime对象中删除C#中日期的时间部分?,c#,datetime,C#,Datetime,我需要删除日期时间的时间部分,或者可能在对象表单中使用以下格式的日期,而不是字符串 06/26/2009 00:00:00:000 我不能使用任何字符串转换方法,因为我需要对象表单中的日期 我首先尝试将日期时间转换为字符串,从中删除特定于时间的日期,但当我再次将其转换回日期时间对象时,它会添加12:00:00 AM。查看该属性 获取此实例的日期组件 使用属性: var dateAndTime = DateTime.Now; var date = dateAndTime.Date; date变

我需要删除日期时间的时间部分,或者可能在
对象
表单中使用以下格式的日期,而不是
字符串

06/26/2009 00:00:00:000
我不能使用任何
字符串
转换方法,因为我需要
对象
表单中的日期

我首先尝试将
日期时间
转换为
字符串
,从中删除特定于时间的日期,但当我再次将其转换回
日期时间
对象
时,它会添加
12:00:00 AM

查看该属性

获取此实例的日期组件

使用属性:

var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;
date
变量将包含日期,时间部分将为
00:00:00


试着建立你自己的结构。DateTime对象将同时具有日期和时间属性将在午夜返回日期

一个选项是分别获取各个值(天/月/年),并将其存储在所需的类型中

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

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

您可以使用格式字符串为输出字符串指定您喜欢的格式

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

阅读更多关于

根据我的经验,上述解决方案都不起作用,可能是因为我想从数据库中删除提取日期的时间,但下面的代码运行良好:

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

如果你从日历上取日期,我们也有时间。这不是所有时候都需要的。使用此选项,我们可以从日期中删除时间。

您不能。NET中的DateTime始终有一个时间,默认为00:00:00:000。DateTime的Date属性也是DateTime(!),因此时间也默认为00:00:00:000


这是.NET Framework中的一个不足之处,可以说.NET中的DateTime违反了

使用ToSortDateString方法。请参阅文档


您可以在Datetime中的唯一日期尝试此选项

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

其中dt是
日期时间

在试图解决原始问题时遇到了这篇文章

我正在使用Asp.Net,经过一些研究,我发现当您绑定到代码中日期的值时,可以删除时间,这样它就不会显示在屏幕上

C#:

aspx:


使用


我很惊讶没有人提到日期时间。今天

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

请参见将变量声明为字符串

例如:

public string dateOfBirth ;
然后指定一个值,如:

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

DateTime对象的日期将忽略时间部分

以下是代码:

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();
输出:

>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
使用一点正则表达式:

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

以以下格式生成日期:dd/mm/yyyy

如果要将其转换为字符串,则可以很容易地这样做

我把date作为你的DateTime对象

date.ToString("d");

这将只提供日期。

供datalist、repeater使用。。在aspx页面中:

创建一个只包含所需属性的结构。然后使用扩展方法从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
        };
    }
}
用法


我知道这是一篇有很多答案的老文章,但我还没有看到这种删除时间部分的方法。假设您有一个名为
myDate
DateTime
变量,其中日期包含时间部分。您可以使用此构造函数从中创建一个新的
DateTime
对象,不带时间部分:

public DateTime(int year, int month, int day);
像这样:

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

这样,您可以在旧对象的基础上创建一个新的
DateTime
对象,将00:00:00作为时间部分。

这种只获取日期而不获取时间的方法

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

输出=2015年5月16日

这可以简单地通过以下方式完成:

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

以上答案都没有解决我在winforms上的问题

仅访问日期的最简单方法是Datetime中的简单函数:

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

您将只在生日字符串中包含日期。

我编写了一个
DateOnly
结构。这在皮肤下使用日期时间,但不公开时间部分:

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);
    }
}
使用系统;
public struct DateOnly:IComparable、IFormattable、IComparable、IEquatable
{
私有日期时间_dateValue;
公共整数比较(对象对象对象)
{
if(obj==null)
{
返回1;
}
DateOnly otherDateOnly=(DateOnly)obj;
if(otherDateOnly!=null)
{
返回ToDateTime().CompareTo(otherDateOnly.ToDateTime());
}
其他的
{
抛出新ArgumentException(“对象不是DateOnly”);
}
}
int IComparable.CompareTo(仅日期其他)
{
返回此.compareToft(其他);
}
public int compareToft(仅日期其他)
{
//如果other不是有效的对象引用,则此实例更大。
如果(其他==new DateOnly())
{
返回1;
}
返回此.ToDateTime().CompareTo(其他.ToDateTime());
}
bool IEquatable.Equals(仅日期其他)
{
返回此.EqualsOfT(其他);
}
public bool EqualsOfT(仅限日期其他)
{
如果(其他==new DateOnly())
{
返回false;
}
if(this.Year==other.Year&&this.Month==other.Month&&this.Day==other.Day)
{
返回true;
}
其他的
{
返回false;
}
}
公共静态日期仅限现在()
{
仅返回新日期(DateTime.Now.Year、DateTime.Now.Month、DateTime.Now.Day);
}
公共静态bool TryParse(字符串s,ref DateOnly result)
{
DateTime dateValue=默认值(DateTime);
if(DateTime.TryParse(s,out dateValue))
{
结果=仅新日期(dateValue.Year、dateValue.Month、dateValue.Day);
返回true;
}
其他的
{
返回false;
}
}
公共静态DateOnly解析(字符串s)
{
DateTime dateValue=默认值(DateTime);
dateValue=DateTime.Parse;
仅返回新日期(dateValue.Year、dateValue.Month、dateValue.Day);
}
公共静态日期仅解析精确(字符串s,字符串形式
DateTime dt = DateTime.Now;
DateOnly result = dt.GetDateOnly();
public DateTime(int year, int month, int day);
myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);
DateTime date = DateTime.Now;
string Strdateonly = date.ToString("d");
var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)
DateTime dt = DateTime.now;
String BirthDate = dt.ToShortDateString();
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);
    }
}
    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);
Date with Time: 9/4/2016 11:42:16 AM

Date Only : 04/09/2016
var date = DateTime.Now
var shortDate = date.ToShortDateString() //will give you 16/01/2019
var date = DateTime.Now
var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019
var date = DateTime.Now.ToShortDateString();