VB.Net 自定义时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43389392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.Net Custom Time Format
提问by Adrian Brown
I have a VB program built in Studio 2017. I need to generate the time in a format which can go on to be used in a filename.
我有一个在 Studio 2017 中构建的 VB 程序。我需要以一种可以继续在文件名中使用的格式生成时间。
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
spits out 12:00:00 for example and the : isn't usable in a filename.
例如,吐出 12:00:00 并且 : 在文件名中不可用。
I could do with either removing the : so it would be 1200000 (not particularly readable but suitable for my purposes) or 12-00-00.
我可以删除 : 所以它是 1200000(不是特别可读但适合我的目的)或 12-00-00。
I have checked hereand can't see any ToString format that will do the trick.
我在这里检查过,看不到任何可以解决问题的 ToString 格式。
My code will put a label (say label1) to the current date and time. Another part will use the Label1.Text to grab the string. So any formatting can happen with Label1.
我的代码将在当前日期和时间上放置一个标签(比如 label1)。另一部分将使用 Label1.Text 来抓取字符串。因此,Label1 可以进行任何格式设置。
For example, it will be used as follows;
例如,它将按如下方式使用;
oDoc = oWord.ActiveDocument
oDoc.saveas2("C:\Test\" & "DocumentTitle" & "-" & label1.text & ".docx"
Is there a way to format the Date string to what I want?
有没有办法将日期字符串格式化为我想要的格式?
回答by Visual Vincent
Why add the colons in the first place?
为什么要首先添加冒号?
DateTime.Now.ToString("yyyy-MM-dd HHmmss")
回答by Mederic
Simply use the String.Replace
只需使用String.Replace
Dim ActualTime as String = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
ActualTime = ActualTime.Replace("/","-").Replace(":","-")
oDoc = oWord.ActiveDocument oDoc.saveas2("C:\Test\" & "DocumentTitle" & "-" & ActualTime & ".docx"
Not the most optimized but clear to understand. Added a one line replace as suggested by Visual Vincent.
不是最优化的,但清晰易懂。按照 Visual Vincent 的建议添加了一行替换。
Make sure to check his solution as well.
一定要检查他的解决方案。

