Here's my input:
sw.WriteLine("{0:MM/dd/yyyy HH:mm:ss tt} ", DateTime.Now + Convert.ToString(newurls[counter]));
and I get this output:
4/4/2016 2:46:57 PM14751
Then when I flip the two inputs like this:
sw.WriteLine(Convert.ToString(newurls[counter]) + "{0:MM/dd/yyyy HH:mm:ss tt} ", DateTime.Now);
I get this output:
1459104/04/2016 14:48:02 PM
Note: newurls[counter]
is changing all the time.
Back on point, I want it so that the DateTime now is in military time, but in front of newurls[counter
. What I mean is, I want the output to be like this:
04/04/2016 14:48:02 PM14591
Why are the times switching back and forth from military and standard?
答案 0 :(得分:4)
sw.WriteLine("{0:MM/dd/yyyy HH:mm:ss tt} ", DateTime.Now + Convert.ToString(newurls[counter]));
should probably be
sw.WriteLine("{0:MM/dd/yyyy HH:mm:ss tt} {1}", DateTime.Now, Convert.ToString(newurls[counter]));
In the first instance you are converting the datetime to a string and then adding it to the Convert.ToString results. In the second instance you are converting it first with your formatter and then concatinating the strings.
In my change above I am adding a placeholder for your second parameter in the string as {1}
, that is where the Convert.ToString(newurls[counter])
will be placed. For more info see Composite Formatting.
答案 1 :(得分:1)
When you are adding:
DateTime.Now + Convert.ToString(newurls[counter])
that's where you lose your date formating
I think what you want is:
sw.WriteLine("{0:MM/dd/yyyy HH:mm:ss tt} {1}", DateTime.Now , Convert.ToString(newurls[counter]));
答案 2 :(得分:1)
您正在处理的问题是您正在处理两种完全不同的格式和值。
在第一个示例中,您将提供字符串格式:
"{0:MM/dd/yyyy HH:mm:ss tt} "
然后提供值
DateTime.Now + Convert.ToString(newurls[counter])
日期的默认ToString()
实现是短通用版本。由于参数0
不是DateTime,因此该值被视为字符串。您只需编写以下内容即可验证:
sw.WriteLine(DateTime.Now + Convert.ToString(newurls[counter]));
解决方案是将不同的组件视为单独的项目:
sw.WriteLine("{0:MM/dd/yyyy HH:mm:ss tt} {1}",
DateTime.Now,
Convert.ToString(newurls[counter]));
您现在可以相互更改{1}
和{0}
的关系,并获得您的期望。如果您使用字符串格式,则从不需要使用+
符号。只需将您的值写为逗号分隔列表,并使用花括号中的数字表示您传递的各个参数。在这种情况下,DateTime.Now
首先被传递,因此我们将其称为{0}
。第二次传递了Convert.ToString(newurls[counter])
,因此我们将其称为{1}
。