00 Votes

C#/.NET: How to write today's date/current time in string

Question by CSchaf | 2014-09-01 at 23:42

I would like to determine the current date and time using C# (C-Sharp, .NET Framework) to be able to write it into a string, so that I can work with it.

Later, I would like to store this timestamp together with some other data, but at the moment I am failing at being able to read out the time at all. Does someone have any idea how to do that? Are there any ready built in methods or functions for that?

ReplyPositiveNegative
0Best Answer0 Votes

You can use DateTime.Now.ToString to store the current date in the string. Depending on how you would like to format your date and time, you can pass another formatting string:

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

string dat = DateTime.Now.ToString("dd-MM-yy");
// 01-01-15

string dat = DateTime.Now.ToString("d.M.yy");
// 1.1.15

string dat = DateTime.Now.ToString("dd.MM.yy HH:mm:ss");
// 01.01.15 00:00:00

string dat = DateTime.Now.ToString("yyyyMMdd");
// 20150101

Hereby, among others, you can use the following format specifiers:

  • "yyyy" for a four-digit year (2014), "yy" for a two-digit year (14)
  • "MM" for a two-digit month with leading zeros, "M" for the month without leading zeros
  • "dd" and "d" accordingly for the day
  • "HH", "H", "mm", "m", "ss" and "s" accordingly for hour, minute and second with or without leading zeros

As you can see in the example above, you can also use other characters such as dots or hyphens between the format specifiers like you want.
2014-09-04 at 20:58

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Determine Week Number

Tutorial | 0 Comments

VirtualBox: Change Date and Time

Tutorial | 10 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.