I am trying to create a unique value using a day,month,hour,minute and seconds. if i create the unique value at "2022/10/10 15:00:00" and i use ToString(), the "00" are truncated to "0"
var today = DateTime.Now;
string key = string.Format("341{0}{1}{2}{3}{4}", today.Date.Day, today.ToString("MM"), today.Hour.ToString(), today.Minute.ToString(), today.Second.ToString());
CodePudding user response:
It's not 00
value. It's DateTime struct with int
properties.
Use interpolation and proper DateTime format:
string key = $"341{today:ddMMHHmmss}"
CodePudding user response:
There are much easier (and more consistent) means of formatting a DateTime into an output string. Just use the ToString() method on your DateTime.
var dateStringIWant = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
More deets here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
CodePudding user response:
Try this :
string.Format("341{0}{1}{2}{3}{4}", today.ToString("dd"), today.ToString("MM"), today.ToString("HH"), today.ToString("mm"), today.ToString("ss"));
CodePudding user response:
today.Hour
, today.Minute
, and today.Second
are all integers, so the value you're converting to a string is the integer 0
, not "00"
. Use ToString("00")
if you want to preserve leading zeroes on them. Or just use a format string for the date to get the output you want.