I want to have the datetime in my file, like this:

Date 2014.03.20 11.41.06 or german 20.03.2014 11.41.06

but it does not work. If i try to convert the DateTime to string i get:

1.1.1 0.0.0 What's wrong with this?

DateTime DateAndTime = new DateTime();

int day = DateAndTime.Date.Day;
int month = DateAndTime.Date.Month;
int year = DateAndTime.Date.Year;

int second = DateAndTime.Date.Second;
int minute = DateAndTime.Date.Minute;
int hour = DateAndTime.Date.Hour;

string sday = day.ToString();

string path = day + "." + month + "." + year + hour +
              "." + minute + "." + second + " test.txt";

FileStream fileStream = new FileStream(expath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
有帮助吗?

解决方案 2

The DateTime value will be 0001.01.01 00.00.00 when using new DateTime(), it's better to use DateTime.Now if you want the current date and time:

var path = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + " test.txt";

Sample

其他提示

You never set a DateTime value, so it defaulted to midnight on January 1st. If you want to use the current date then use DateTime.Now:

DateTime DateAndTime = DateTime.Now;

You can use CultureInfo to get the correct formatting for various regions. Since you mentioned German:

using System.Globalization;

CultureInfo deDE = new CultureInfo("de-DE");
string DateAndTime = DateTime.Now.ToString(deDE);

It will give you the following output, though:

20.03.2014 14:39:12

Example from http://www.dotnetperls.com/filename-datetime

Just do

string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin", DateTime.Now);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top