For an API call, I need to represent a DateTime as a string including the milliseconds, but in a format that doesn't seem to be supported by DateTime.ToString
.
对于API调用,我需要将DateTime表示为包含毫秒的字符串,但其格式似乎不受DateTime.ToString支持。
Specifically, I need to capture the date including 3 decimal digits of the milliseconds (that is, milliseconds but no microseconds) and send that left padded with zeroes to 4 place. So if the actual milliseconds are 123
, I need to send 0123
. (I am aware that milliseconds are always <1000 and so one would never need 4 places, but I didn't design and have no control over this API.)
具体来说,我需要捕获日期,包括毫秒的3个十进制数字(即毫秒但没有微秒),并将左边填充的零发送到4位。因此,如果实际的毫秒数是123,我需要发送0123.(我知道毫秒总是<1000,所以一个人永远不需要4个位置,但我没有设计并且无法控制这个API。)
I wanted to do the simple thing and use a format like yyyyMMddHHmmssffff
, but it seems that this shows milliseconds to 4 digits of precision, not three digits with left padding.
我想做一些简单的事情,并使用像yyyyMMddHHmmssffff这样的格式,但似乎这显示毫秒到4位数的精度,而不是三位左边填充。
I know that I could separate the date into second and sub-second resolution, format them separately, and concatenate, but this seems klunky.
我知道我可以将日期分为秒和亚秒分辨率,单独格式化,并连接,但这看起来很笨拙。
Is there a built-in format string that does what I need?
是否有内置格式字符串可以满足我的需求?
2 个解决方案
#1
1
Since you want the 0 to be always 0 no matter what, no need to make it dynamic, you can simply add it as a char:
既然你想让0总是0,不管是什么,不需要让它动态,你只需将它添加为char:
yyyyMMddHHmmss0fff
#2
2
Since that's a highly-misleading and user-error-prone way to represent a date, given that "0123" would be interpreted as 12.3 milliseconds, I would say no, there's no way to do that except the "klunky" way you mentioned.
由于这是一种极具误导性和用户错误的方式来表示日期,因为“0123”将被解释为12.3毫秒,我会说不,除了你提到的“klunky”方式之外,没有办法做到这一点。
#1
1
Since you want the 0 to be always 0 no matter what, no need to make it dynamic, you can simply add it as a char:
既然你想让0总是0,不管是什么,不需要让它动态,你只需将它添加为char:
yyyyMMddHHmmss0fff
#2
2
Since that's a highly-misleading and user-error-prone way to represent a date, given that "0123" would be interpreted as 12.3 milliseconds, I would say no, there's no way to do that except the "klunky" way you mentioned.
由于这是一种极具误导性和用户错误的方式来表示日期,因为“0123”将被解释为12.3毫秒,我会说不,除了你提到的“klunky”方式之外,没有办法做到这一点。