1

I have for example following date time

 DateTime dt = new DateTime(2013,18,04,22,23,0);

this date should be represented like

18-04-2013 22:23    Environment.NewLine

Worth to mention is there are spaces between number 3 (of 22:23) and Environment.NewLine. So, field length is 20characters from beginning to E letter (of Environment.NewLine).

How can I represent date in this format with spaces?

4

3 回答 3

3

我将使用标准日期格式和非特定日期字符串格式代码的组合:

string.Format("{0:MM-dd-yyyy HH:mm}    \n", dt);

或者如果长度“20”很重要:

string.Format("{0,-20:MM-dd-yyyy HH:mm}\n", dt);

这有效地将字符串“填充”为 20 个字符并左对齐。这样,即使有人决定更改日期格式(例如,不要用零填充),您仍然只有 20 个字符

于 2013-04-18T13:01:25.363 回答
2
string.Format("{0,-20}  {1}", DateTime.ToString("MM-dd-yyyy HH:mm"), Environment.NewLine);
于 2013-04-18T13:01:05.973 回答
0

假设您修复了DateTime作业,因此月份在前一天:

DateTime dt = new DateTime(2013, 4, 18, 22, 23, 0);
String.Format("{0,-20}{1}",
    dt.ToString("dd-MM-yyyy HH:mm"),
    "Environment.NewLine" //*/ Environment.NewLine // Whichever you want
);

Format允许您在格式化程序中指定空格填充,因此{0,-20}表示以 20 个字符的列显示,左对齐。同样,{0,20}会做 20 个字符,右对齐。

于 2013-04-18T13:10:16.083 回答