Reputation: 506
I have the following log to a text file method: I wanted to include a time stamp like this (2014-01-23 09:42:20.020 AM) but when I look at my log file it doesn't include the .020 time. Did I miss to format something?
// Build timestamp string
var currentDateTime = DateTime.Now;
string timeStampString = currentDateTime.ToString("ddMMyyyy_HHmmssms");
// Build filename messages, concat timestamp and .txt extension.
string debugFileName = "C:\\Test" + timeStampString + ".txt";
var inboundMessageLog = new StreamWriter(debugFileName, false, System.Text.Encoding.Default);
// Write to the file:
inboundMessageLog.WriteLine(DateTime.Now);
inboundMessageLog.WriteLine("TimeStampString = {0}", timeStampString);
inboundMessageLog.WriteLine("Inbound message = {0}", strMessage);
inboundMessageLog.Close();
// -------------------------------------------------------------------------------------------
}
Thank you for your time.
UPDATE:
This format:
string timeStampString = currentDateTime.ToString("yyyy-MM-dd hh:mm:ss:fff tt") or .fff tt;
didn't work for me. I see my logs only when I use
string timeStampString = currentDateTime.ToString("yyyyMMdd hhmmss");
Upvotes: 3
Views: 3218
Reputation: 26209
Problem : You are using ms
to represent the Milliseconds.
Solution : there is no custom format ms
You need to use fff
to represent MilliSeconds
fff The milliseconds in a date and time value.
if you want to get the Date and Time in the format of (2014-01-23 09:42:20.020 AM)
You need to use this format yyyy-MM-dd hh:mm:ss.fff tt
Try This:
string timeStampString = currentDateTime.ToString("yyyy-MM-dd hh:mm:ss.fff tt");
EDIT : if you want custome format as dd-MM-yyyy_HH:mm:ss:fff
Try This:
string timeStampString = currentDateTime.ToString("dd-MM-yyyy_HH:mm:ss:fff tt");
Explanation:
yyyy
- Year in 4 digits
MM
- Month in two digits
dd
- Date in two digits
hh
- Hours in two digits.
mm
- Minutes in two digits.
ss
- Seconds in two digits.
fff
- Milliseconds
tt
- AM or PM.
See this for more information : DateTime custom formats
Upvotes: 7