문제

I am writing files to my harddrive,The filename is build like this:

String.Format("{0:yyyy-MM-dd_hh-mm-ss}.txt", DateTime.Now)

So the filename is "2010-09-20_09-47-04.txt" for example. Now I want to show those filenames in a dropdown, but with another format. The format should be dd.MM.yyyy HH:mm:ss. How can I do that, or is there a better approach?

Thanks :)

도움이 되었습니까?

해결책

I tried this on console and it did the job.

Imports System.Globalization
Module Module1

Sub Main()
    Dim enUS As New CultureInfo("en-US")
    Dim d As String = Format(DateTime.Now, "yyyy-MM-dd_hh-mm-ss")
    Dim da As Date = DateTime.ParseExact(d, "yyyy-MM-dd_hh-mm-ss", enUS)
    Console.WriteLine("Date from filename: {0}", d)
    Console.WriteLine("Date formated as date: {0}", Format(da, "dd.MM.yyyy HH:mm:ss"))

End Sub
End Module

Hope it helps.

다른 팁

You can use DateTime.ParseExact with the same format you use to build name to parse the file name into DateTime object and than convert it to the desired format with ToString

You can parse it back into a DateTime, then format it to your display format.

string FileName = "2010-09-20_09-47-04";
DateTime dt = new DateTime();
dt = DateTime.Parse(FileName.Substring(0, 10));
dt.ToString("dd.MM.yyyy");

you can parse your filename using a regular expression:

Regex r = new Regex("(\d{4})-(\d{2})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2}).txt");
Match m = r.Match(fileName);

Update: The DateTime.Parse approach proposed by others is much more appropriate.

Since you are working with dates, you might want to consider using the created date or modified date of the file instead?

FileInfo f = new FileInfo(fileName);
string title = String.Format("{0:dd.MM.yyyy}", f.CreationTime);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top