我有一个文本文件方法的以下日志:我想要包含这样的时间戳(2014-01-23 09:42:20.020 AM)但是当我查看我的日志文件时它不包括.020时间.我错过了格式化的东西吗?
// 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();
// -------------------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
}
感谢您的时间.
更新:
这种格式:
string timeStampString = currentDateTime.ToString("yyyy-MM-dd hh:mm:ss:fff tt") or .fff tt;
Run Code Online (Sandbox Code Playgroud)
不适合我.我只在使用时看到我的日志
string timeStampString = currentDateTime.ToString("yyyyMMdd hhmmss");
Run Code Online (Sandbox Code Playgroud)
问题:您ms用来表示毫秒.
解决方案:ms
您无需使用自定义格式fff进行表示MilliSeconds
fff日期和时间值中的毫秒数.
如果你想以格式获得日期和时间 (2014-01-23 09:42:20.020 AM)
您需要使用此格式 yyyy-MM-dd hh:mm:ss.fff tt
试试这个:
string timeStampString = currentDateTime.ToString("yyyy-MM-dd hh:mm:ss.fff tt");
Run Code Online (Sandbox Code Playgroud)
编辑:如果你想要自定义格式dd-MM-yyyy_HH:mm:ss:fff
试试这个:
string timeStampString = currentDateTime.ToString("dd-MM-yyyy_HH:mm:ss:fff tt");
Run Code Online (Sandbox Code Playgroud)
说明:
yyyy- 年的4位数字
MM - 月 两位数
dd - 日期两位数
hh - 两位数的小时数.
mm - 两位数分钟.
ss - 两位数秒.
有关更多信息,请参阅此内容:DateTime自定义格式