I'm trying to format content of my file like this:
0126252019-05-06 14:47:06 1098500020
But everytime I'm getting this results:
01262524. 5. 2019. 14:47:08 1098500020
Obliviously date and time are not formated as I wanted.
Here is my code:
StreamWriter file = new System.IO.StreamWriter("C:\\MyMainFolder\\MyFilesFolder\\" + 15050 + ".flr");
file.WriteLine(12625.ToString("D6") + string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now + " " + 1098500020));
file.Close();
I've tried to format DateTime.Now
as I wrote
string.Format("{0:yyyy-MM-dd HH:mm:ss}"
But looks like its not working
Thanks guys
Cheers!
The problem is that +
is applied as string concatenation in the expression below:
string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now + " " + 1098500020);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// C# makes this one string, and passes it for formatting.
Moving the concatenation that you plan to do inside the format string will fix the problem:
string.Format("{0:yyyy-MM-dd HH:mm:ss} 1098500020", DateTime.Now);
You are passing DateTime.Now + " " + 1098500020
to string.Format
which isn't going to be parsed by that format string you have specified. To fix that you should move the )
.
However, you should create the entire string, including the prefix , with string.Format
, or for clearer code use string interpolation , for example:
var someInteger = 12625;
var line = $"{someInteger:D6}{DateTime.Now:yyyy-MM-dd HH:mm:ss} 1098500020";
consider using
string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now) + " " + 1098500020
Pass the date only to string format
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.