C#: How would I get the current time into a string?
I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then
DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
would return
01.05.2009 6?01 PM
In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:
DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")
or
DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt")
which would now return
01/05/2009 6:01 PM
EDIT:
Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.
DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")
Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.
DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")
Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.
DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");
"6:01 PM" in US, "18:01" in UK.
DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");
"6:01:04 PM" in US, "18:01:04" in UK.
DateTime.Now.ToString()
DateTime.Now.ToString("G");
"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.
Many other options are available. See docs for standard date and time format strings and custom date and time format strings.
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.