Get current date only in C#

2019-01-13 03:59发布

I am able to get date and time using:

DateTime now = DateTime.Now;

How can I get the current date and time separately in DateTime format itself?

I am not using DateTime picker dialog box in ASP.net (C#).

9条回答
贼婆χ
2楼-- · 2019-01-13 04:13

You can use following code to get the date and time separately.

DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];

You can also, check the MSDN for more information.

查看更多
Explosion°爆炸
3楼-- · 2019-01-13 04:14
for month     DateTime.Now.ToString("MM");
for Date      DateTime.Now.ToString("dd");
for year      DateTime.Now.ToString("yyyy");
查看更多
唯我独甜
4楼-- · 2019-01-13 04:17
string now = Convert.ToString(DateTime.Now.ToShortDateString());
Console.WriteLine(now);
Console.ReadLine();
查看更多
家丑人穷心不美
5楼-- · 2019-01-13 04:19

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...

查看更多
太酷不给撩
6楼-- · 2019-01-13 04:21

Current Time :

DateTime.Now.ToString("HH:mm:ss");

Current Date :

DateTime.Today.ToString("dd-MM-yyyy");
查看更多
叛逆
7楼-- · 2019-01-13 04:24

Use

txtdate.Text = DateTime.Today.ToString("dd-MM-yyyy");
查看更多
登录 后发表回答