Adrian Brown Adrian Brown - 2 months ago 12
Vb.net Question

VB.Net Custom Time Format

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.

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")


spits out 12:00:00 for example and the : isn't usable in a filename.

I could do with either removing the : so it would be 1200000 (not particularly readable but suitable for my purposes) or 12-00-00.

I have checked here and can't see any ToString format that will do the trick.

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.

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?

Answer

Simply use the 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.

Make sure to check his solution as well.