Using a datetime as filename and parse the filename afterwards?

别等时光非礼了梦想. 提交于 2019-12-06 05:09:16
Besnik

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!