String concatenation with padded integers

67 views Asked by At
var dateAndTime = DateTime.Now;
string lastTwoDigitsOfYear = DateTime.Now.ToString("yy");

int digitPlaceHolder;
digitPlaceHolder = int.Parse(lastTwoDigitsOfYear);

int stringLength = int.Parse(lastTwoDigitsOfYear);

stringLength = int.Parse(lastTwoDigitsOfYear).ToString("D4") + request.RequestId;

What I'm trying to accomplish is the following:

  • Parsing DateTime to get the last two numbers of the year [15]
  • Adding and concatenating the [15] with an Id as well as 4 zeroes padding it.

So in the end it would be: [15][0001][id] This combined will result in a new variable which can be used. I'm just having trouble converting then concatenating

Cannot implicitly convert int to string

Is the error I'm receiving (obviously), but is there an elegant way of solving this error?

1

There are 1 answers

2
Hossein Narimani Rad On

This may helps:

var value = string.Format("[{0}][{1:D4}][{2}]",
                           DateTime.Now.ToString("yy"), 
                           1, // or any other int value or variable
                           request.RequestId);