0

I would like to write some information to log files. First I want to write down the date, then the time and after that the log message. An example would be

11.02.2019 | 09:36:24 | Something finished

Currently I get logged this

11.02.2019 00:00:00 | 09:36:24 | ...
11.02.2019 00:00:00 | 09:36:24 | ...
11.02.2019 00:00:00 | 09:36:24 | ...

I use this code for the date and time handling

private string GetDateTimestamp()
{
    string currentDate = DateTime.Now.Date.ToString();
    string currentTime = DateTime.Now.ToLongTimeString();
    return $"{currentDate} | {currentTime} | ";
}

How can I remove the trailing zeros from the date when using c# DateTime.Now.Date?

2 Answers2

2

You can use ToShortDateString. In addition, you don't need to use the Date property:

string currentDate = DateTime.Now.ToShortDateString();

As an alternative, you can specify the DateTime format also like this (d for short date format, T for long time format):

private string GetDateTimestamp()
{
    var dtNow = DateTime.Now;
    return $"{dtNow:d} | {dtNow:T} | ";
}
Markus
  • 20,838
  • 4
  • 31
  • 55
1

Same way you filtered out the date from your currentTime

string currentDate = DateTime.Now.Date.ToShortDateString();

Additional you could also make use of the ToString() overload to provide your own format and do it all in 1 step:

var result = DateTime.Now.Date.ToString("yyyy.MM.dd | HH:mm:ss | ");
NotFound
  • 5,005
  • 2
  • 13
  • 33