简体   繁体   中英

DateTime.ToString()?

I am having a problem. How do I show the text of my Date correctly?

using DateTime.Now I was able to recieve the date & time the computers clock is set to currently, however, when I try to parse into a string format, it also shows the date like: 12-04-2012 12:38 but I was trying to get the time string only, like 12:38 only?

What I tried so far was Console.WriteLine(DateTime.Now.ToString("00:00:00"));

But it did not work =/

DateTime has a ToShortTimeString method defined:

DateTime.Now.ToShortTimeString()

Or, you can use a custom format string :

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

Alternatively, use the standard format string for short time format :

DateTime.Now.ToString("t")

One solution that works for a lot of problems is reading documentation : http://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.80%29.aspx

Using Format "t" seems to do what you want

Just use this:

DateTime.Now.ToString("hh:mm");

or

DateTime.Now.ToShortTimeString();

For using DateTime.Now.ToString() , this link is very useful and explains all patterns: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Patterns are like following:

DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss")

Tuesday, 22 August 2006 06:30:07

DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")

Tue, 22 Aug 2006 06:30:07 GMT

DateTime.Now.ToString("MM/dd/yyyy")

08/22/2006

Try to format like this:

Console.WriteLine(DateTime.Now.ToString("hh:mm:ss"));

or

Console.WriteLine(DateTime.Now.ToString("hh:mm"));

But my favorite is

Console.WriteLine(DateTime.Now.ToShortTimeString());

You could try:

var dt = DateTime.Now.TimeOfDay; dt.ToString().Substring(0, 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM