How to get the current date without the time?

后端 未结 12 1663
青春惊慌失措
青春惊慌失措 2020-11-29 00:50

I am able to get date and time using:

DateTime now = DateTime.Now;

How can I get the current date and time separately in the DateTime forma

12条回答
  •  甜味超标
    2020-11-29 01:23

    Well, you can get just today's date as a DateTime using the Today property:

     DateTime today = DateTime.Today;
    

    or more generally, you can use the Date property. For example, if you wanted the UTC date you could use:

     DateTime dateTime = DateTime.UtcNow.Date;
    

    It's not very clear whether that's what you need or not though... if you're just looking to print the date, you can use:

    Console.WriteLine(dateTime.ToString("d"));
    

    or use an explicit format:

    Console.WriteLine(dateTime.ToString("dd/MM/yyyy"));
    

    See more about standard and custom date/time format strings. Depending on your situation you may also want to specify the culture.

    If you want a more expressive date/time API which allows you to talk about dates separately from times, you might want to look at the Noda Time project which I started. It's not ready for production just yet, but we'd love to hear what you'd like to do with it...

提交回复
热议问题