I am currently using the following line:
w.Write(DateTime.Now.ToString("MM/dd/yyyy,HH:mm:ss"));
and it gives and output like:
05/23/2011,14:24:54
What I need is quotations around the date and time, the output should look like this:
"05/23/2011","14:24:54"
any thoughts on how to "break up" datetime, and get quotes around each piece?
Try String.Format
:
w.Write(String.Format("\"{0:MM/dd/yyyy}\",\"{0:HH:mm:ss}\"", DateTime.Now));
DateTime.Now.ToString("\\\"MM/dd/yyyy\\\",\\\"HH:mm:ss\\\"")
This will do the trick, too.
string format = @"{0:\""MM/dd/yyyy\"",\""HH:mm:ss\""}" ;
string s = string.Format(format,DateTime.Now) ;
as will this:
string format = @"{0:'\""'MM/dd/yyyy'\""','\""'HH:mm:ss'\""'}" ;
string s = string.Format(format,DateTime.Now) ;
and this
string format = @"{0:""\""""MM/dd/yyyy""\"""",""\""""HH:mm:ss""\""""}" ;
string s = string.Format(format,DateTime.Now) ;
The introduction of a literal double quote ( "
) or apostrophe ( '
) in a DateTime or Numeric format strings introduces literal text. The embedded literal quote/apostrophe must be balanced — they act as an embedded quoted string literal in the format string. To get a double quote or apostrophe it needs to be preceded with a backslash.
John Sheehan's formatting cheatsheets makes note of this...feature, but insofar as I can tell, the CLR documentation is (and always has been) incorrect WRT this: the docs on custom date/time and numeric format strings just says that "[any other character] is copied to the result string unchanged.".
The following version, though obvious, will not work:
w.Write(DateTime.Now.ToString("\"MM/dd/yyyy\",\"HH:mm:ss\""));
This will output:
MM/dd/yyyy,HH:mm:ss
So don't do that.
string part1 = DateTime.Now.ToString("MM/dd/yyyy");
string part2 = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine("\""+part1+"\",\""+part2+"\"");
Works just fine. May not be the best way though
I'm not sure about the type of w
but if it supports the standard set of Write
overloads the following should work.
w.Write(@"""{0}""", DateTime.Now.ToString(@"MM/dd/yyyy"",""HH:mm:ss")));
If not then you can do the following
var msg = String.Format(@"""{0}""", DateTime.Now.ToString(@"MM/dd/yyyy"",""HH:mm:ss"))));
w.Write(msg);
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.