CSharper CSharper - 2 months ago 8
C# Question

Convert int to string in specific format

I have a int which I want to convert to string in specific format.

For example,
-1 to -01:00

It is easy if I have positive number (i.e 1 to 01:00). I can use following code:

var time = 6;
var convertTime = "0" + time + ":00";


Output:

06:00


I am not sure how to achieve same with negative number.

var time = -6;
var convertTime = /* what to do here */ + time + ":00";


Desired Output:

-06:00

Answer

Just use string.Format for that

int time = -6;
var convertTime = string.Format("{0:00}:00", time);

Or if you have C# 6 you can do an interpolated string.

var convertTime = $"{time:00}:00";