使用命令行或批处理文件中的日期和时间创建文件名的最简单方法
我需要将日期/时间附加到一天中多次生成的一些测试日志文件。有些人建议这样做:
set CUR_YYYY=%date:~10,4%
set CUR_MM=%date:~4,2%
set CUR_DD=%date:~7,2%
set CUR_NN=%time:~3,2%
set CUR_SS=%time:~6,2%
set CUR_MS=%time:~9,2%
set SUBFILENAME=%CUR_YYYY%%CUR_MM%%CUR_DD%-%CUR_HH%%CUR_NN%%CUR_SS%
然后将它们连接在一起,但我觉得这是不对的。我想知道是否有更好或更简洁的方法?我想会有一个简单的解决方案,因为需求很普遍。
谢谢!
I need to append date/time to some test log files generated multiple times in a day. Some suggest doing it like:
set CUR_YYYY=%date:~10,4%
set CUR_MM=%date:~4,2%
set CUR_DD=%date:~7,2%
set CUR_NN=%time:~3,2%
set CUR_SS=%time:~6,2%
set CUR_MS=%time:~9,2%
set SUBFILENAME=%CUR_YYYY%%CUR_MM%%CUR_DD%-%CUR_HH%%CUR_NN%%CUR_SS%
And then concatenate them together but I feel it's just not right. I wonder if there is a better or more concise way of doing it? I imagine there would be a simple solution because the need is quite common.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,首先,数据/时间格式化实际上在任何编程语言中都是一件大事。例如,只需查看 C# DateTime 类中的一长串 ToString() 方法,您就会了解它是什么样的。
对于您的特定任务,假设您的区域设置日期使用“-”,区域设置时间使用“:”作为分隔符(您可以回显日期/时间来验证:)
如果您不挑剔,生成文件名的最简单方法是下面,您可以根据您自己的语言环境替换“-”和“:”字符,这将为您在大多数系统中提供有效的文件名。
如果您只想在命名中使用字母数字字符,那么可能是一组更清晰的命令:
这应该给您类似的内容
但是,如果您需要处理应用程序全球化,最好首先使用 PowerShell(在 Windows 上)等工具将日期/时间格式化为预定义的字符串格式。然后它将使任何后续的字符串操作变得更容易。
Well, first of all, data/time formatting is actually a big thing in any programming languages. Just look at the long list of ToString() methods in C# DateTime class, for example, will give you an idea what it is like.
For your particular task, assuming that your locale date using "-" and your locale time using ":" as separators (you can echo date/time to verify:)
If you are not picky, the simplest way to generate a file name is below, and you may replace the '-' and ':' characters according to your own locale, which will give you a valid file name in most systems.
If you want only alphanumeric characters in your naming, then probably a cleaner set of commands:
That should give you something like
However, if you need to deal with application globalization, it's always best to format date/time to a predefined string format using something like PowerShell (on Windows) as the first step. It will then make any subsequent string manipulations easier.