开发者

How do I convert a DateTime to a Date in C#

I can't believe how long it's taken me to fail at finding the answer to this seemingly obvious question.

Date SomeRandomMadeUpDate = DateTime.Now.AddMonths(randomMonths).Date;

Cannot implicitly convert type 'System.DateTime' to 'System.Date' I can even call:

Date.Now

but calling .AddDays o开发者_开发百科n it returns a DateTime.

Again, the question is: How do I turn a C# DateTime into a C# Date


There is no "Date" type as such. It's all DateTimes. It's just that when you call .Date, you are getting that DateTime as of midnight on that day.

If you're talking about the "Date" data type in VB.NET, that's the same thing as DateTime, believe it or not.


.NET doesn't have a type representing just a date - it's problems like this that made me start Noda Time (which isn't even nearly ready for production yet).

DateTime.Date returns another DateTime with the same date as the original, but at midnight. That's basically the closest there is to a Date type in .NET :( Note that if you want today's date then DateTime.Today is a simpler way of calling DateTime.Now.Date.

I've no idea why the compiler is giving an error message that suggests there is a System.Date type - it doesn't on my machine:

using System;

class Test
{
    static void Main()
    {
        Date today = DateTime.Now.Date;
    }
}

Gives this error:

Test.cs(7,9): error CS0246: The type or namespace name 'Date' could not be found (are you missing a using directive or an assembly reference?)

Can you give a similar short but complete program which shows the error message you're getting? Do you have some other library referenced which does have a System.Date type? (As Tommy Carlier suggests, perhaps System.Dataflow?)


I had to look it up, because I didn't know there was a Date-type in .NET 4.0, but apparently there is one in System.Dataflow.dll. Just use the constructor, with the DateTime as the argument:

Date d = new Date(dt);


You can construct a new Date object from a DateTime object:

Date d = new Date(DateTime.Now);

See http://msdn.microsoft.com/en-us/library/system.date.date(VS.85).aspx


Try doing the following

string onlyDate = DateTime.Now.ToString("dd/MM/yyyy");   

this will return Only the date as a string so i think you can use it as

 Date dateNow = new Date(onlyDate );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜