How to Create a Text Filename with DateTime using C# - c#

I want to create a Filename with DateTime.Now to store the errors that catched using Exception Handling everyday.
I used DateTime.ToFileTime, but the format appending for not in date format.
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToFileTime()+ ".txt";
FileStream fi = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw1 = new StreamWriter(fi);
sw1.WriteLine(DateTime.Now + "" + ex.message);
I am Expecting the filename like "ErrorCollector17/08/2019"

You are not allowed to create filename which contains any of following characters: /:*?"<>| on Windows, you can do like this
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToString("dd-MM-yyyy")+ ".txt"

You can try to use ToString function with a format.
DateTime.Now.ToString("dd/MM/yyyy",new System.Globalization.CultureInfo("en-US"));
c# online
As Soundararajan say I would suggest you use
"ddMMyyyy"
or
"dd-MM-yyyy"
due to the system will confuse your path contain \

shortest answer would be the code below:
DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
DateTime.Now gets the current date and time based on your computer's clock.
.ToString(...) converts the DateTime object into a string with optional formatting inside as parameters.
"yyyyMMddHHmmss" is a pattern for how you want the DateTime object be mapped in a string manner where. assuming your computer's clock is currently ticked at "August 8, 2019 12:34:56 PM", then:
yyyy = is a 4 digit year as 2019
MM = is a 2 digit month equivalent such as 08
dd = is a 2 digit day of the year such as 08
HH = is a 2 digit hour equivalent in 24 Hours format such as 12
mm = is a 2 digit minute such as 34
ss = is a 2 digit second such as 56
and the output would be 20190808123456. Note that the arrangement of year, month, date, hour, minute, or even second can be in no specific order.
CultureInfo.InvariantCulture is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings (via source)
note that we removed special characters separating different parts of the DateTime object to prevent issues when filenames on Windows.

Related

C# build date as string with leading 0s and no separators

I have a date. I would like to read out all the date parts into separate strings with leading 0s where applicable and then concatenate them to create a date string that is just numbers without any separators.
For example:
DateTime dt = DateTime.Now;
string year = dt.Year.ToString();
string month = dt.Month.ToString();
string day = dt.Day.ToString();
string hour = dt.Hour.ToString();
string minutes = dt.Minute.ToString();
string seconds = dt.Second.ToString();
string finalDt = string.Concat(year, month, day, hour, minutes, seconds);
I would like month to be 01 if it is January, day to be 03 if it is the third day, and likewise with hour, year, seconds. Is there a way to accomplish that without having to check the count for each datepart and pad it with a leading 0?
If there is a better way to accomplish what I'm trying to do overall, then I would like suggestions.
You can use DateTime.ToString(string format) for this purpse:
dt.ToString("yyyyMMddHHmmss")
Or if you still want to do each part separately:
string year = dt.Year.ToString("0000");
string month = dt.Month.ToString("00");
string day = dt.Day.ToString("00");
string hour = dt.Hour.ToString("00");
string minutes = dt.Minute.ToString("00");
string seconds = dt.Second.ToString("00");
What about using custom format-string in the DateTime.ToString method:
DateTime.Now.ToString("yyyyMMddhhmmss");
The DateTime type supports many ways of formatting, so you can build up the resulting format from individual "components". Refer to the Docs to see all the options available.

How can i create this format of date time directory but with my format?

The test i did is:
string date = DateTime.Now.ToString("ddd dd.MM.yyyy");
string time = DateTime.Now.ToString("HH.mm tt");
string format = "{0} from {1} At {2}";
string cp = string.Format(format, "", date, time);
Directory.CreateDirectory(#"c:\\temp\\" + cp);
The result in the variable cp is: from Fri 20.01.2017 At 09.27 AM
And there is no problem to create this directory.
This is my code:
for (int i = 0; i < countriesNames.Count(); i++)
{
string pathDateTime = urls[0].Substring(48, 12);
string pathDateTimeLast = urls[urls.Count - 1].Substring(48, 12);
var d = DateTime.ParseExact(pathDateTime, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
var e = DateTime.ParseExact(pathDateTimeLast, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
string country = countriesNames[i].Substring(15);
string f = "{0} from {1} At {2} until {3}";
string countryPath = countriesMainPath + "\\" + country + "\\" + string.Format(f, "", d,e);
if (!Directory.Exists(countryPath))
{
Directory.CreateDirectory(countryPath);
}
countryPaths.Add(countryPath);
}
The way i did it with the 'f' variable is not right and not working fine give me exception.
In my code in the variable 'd' there is 20/01/2017 05:15:00
And in variable 'e' 20/01/2017 07:30:00
But i can't create this directories.
So i want to format my date and time after extracting them to be like the format in the first example: from Fri 20.01.2017 At 09.27 AM but with my date and time.
For example my directory should be something like:
from Fri 20.1.2017 At 05:15 AM Until 20.1.2017 At 07:30 AM
Then to create this directory: "from Fri 20.1.2017 At 05:15 AM Until 20.1.2017 At 07:30 AM"
The question is how do i format my dates and times after parsed to this format ?
You are trying to create a path by formatting dates using your current locale's default (long) format. In most countries the date separator is / and the time separator is always :. This results in invalid paths.
It's a bit hard to understand what format you want to use, since you mix calls to String.Format and concatenate the results. It seems that the original path should be:
var cp=String.Format(#"c:\temp\From {0:ddd dd.MM.yyyy} At {0:HH.mm tt}",DateTime.Now);
or
var root="c:\temp\";
var partialPath = String.Format("From {0:ddd dd.MM.yyyy} At {0:HH.mm tt}",DateTime.Now)
var cp=Path.Combine(root,partialPath);
You don't need to format each component separately. If you check the documentation of String.Format you'll see that you can use a composite format string for each placeholder.
The country path seems to be
var partialPath = String.Format(#"{0}\from {1:ddd dd.MM.yyyy} At {1:HH.mm tt} until {2:HH.mm tt}",
country,d,e);
var countryPath =Path.Combine(countriesMainPath,partialPath);
That said, I wouldn't use that date format. The resulting folder names can't be sorted in a meaningful way making it difficult for users to find folders by date. I'd use the yyyy-MM-dd format, or yyyy-MM-dd ddd if the name of the day is really necessary.

String was not recognized as a valid DateTime on DateTime.ParseExact

I know there is a lot of asked question here about DateTime but I saw them all already and seems not to find the right solution for my case.
Here is my code:
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
This is throwing me an Exception.
Here is the value of the variables:
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
You should use format "m/dd/yyyy" because datestring becomes 1/22/2004
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "m/dd/yyyy", new CultureInfo("en-us"));
Unfortunately, both answers are wrong.
So, we all agree your result string will be "1/22/2004". Before looking which formats exactly matches your characters, let's look at your string is a standard date and time format for en-US culture or not.
DateTime.Parse("1/22/2004",
CultureInfo.GetCultureInfo("en-US")) // 22 January 2004 00:00:00
BANG!
We have a DateTime perfectly. But what if our string wouldn't be a standard date and time format for en-US culture? Then we can specify our format with DateTime.TryParseExact method. Let's look at which formats we can use to parsing our string.
1 matches with "M" custom format specifier which is from 1 to 12 and single-digit month is formatted without a leading zero.
/ is a DateSeparator and we can use it the same in our format because en-US culture has / as a DateSeparator already. Remember, "/" custom format specifier has a special meaning of replace me with current culture or supplied culture date separator
22 matches with "dd" custom format string which is from 01 to 31 and single-digit days is formatted with a leading zero. Remember, you can also use d format specifier in such a case but using wider formats is recommended.
2004 matches with "yyyy" custom format specifier which represents the year with a four digits.
So, the right format will be M/dd/yyyy in result.
string s = "1/22/2004";
DateTime dt;
if(DateTime.TryParseExact(s, "M/dd/yyyy", CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt); // 22 January 2004 00:00:00
}
You are referring to wrong format, so obviously it will throw exception. Below is what you are doing
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
string ex = partialDate + dtfi.DateSeparator + _baseDate.ToString();
which gives you 1/22/2014 i.e., MM/dd/yyyy
and in code you are referring to
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
Try using correct Format, to get the right result.

DateTime's ToLongString method doesn't return day name

I'm currently using .NET's DateTime's ToLongDateString() method to parse a date string.
For some cultures this works fine:
US: Wednesday, May 16, 2001
But for a few other cultures the day name is omitted (examples are Dutch, Hungarian and Icelandic cultures).
NL: 16 mei 2001
The DayNames arrays of these cultures contain the proper names for every day of the week, but for some reason they aren't used in a long date string.
I tried using the DateTimeFormat.DayNames [i] + "D" formatting solution, but it didn't work here because it would lead to double day names on cultures that do already show the day name.
US: Wednesday Wednesday, May 16, 2001
NL: woensdag 16 mei 2001
Is there any way to make the day name appear for cultures that omit it by default?
Thats correct.
.NET does what it should do, if you have a look at the regional settings of a windows pc you can change the culture and see whats displayed in the Date (long) field and you will see the following:
for Dutch:
d. MMMM YYYY
for Hungarian:
YYYY. MMMM d.
for Icelandic:
d. MMMM YYYY
You will have to add it manually if you really like to have it for all of them, or force a certain format layout with
DateTime.Now.ToString("dddd, dd MM YYYY");
Have a look at this page to see where the regional settings are found on a windows 7 pc:
http://windows.microsoft.com/en-us/windows7/change-the-country-or-region-setting
Many cultures have multiple long date patterns and you can select from them the first one which contains a day of the week pattern:
static void Main(string[] args)
{
foreach (var cultureInfo in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures))
{
string longDateWithDayOfWeek = null;
foreach (var pattern in cultureInfo.DateTimeFormat.GetAllDateTimePatterns('D'))
{
if (pattern.Contains("ddd"))
{
longDateWithDayOfWeek = pattern;
break;
}
}
bool isFallbackRequired = string.IsNullOrEmpty(longDateWithDayOfWeek);
if (isFallbackRequired)
{
longDateWithDayOfWeek = "dddd, " + cultureInfo.DateTimeFormat.LongDatePattern;
}
System.Console.WriteLine("{0} - {1} {2}", cultureInfo.Name, longDateWithDayOfWeek, (isFallbackRequired) ? " (generated)" : string.Empty);
}
}
Dutch and Icelandic are supported this way, while Hungarian will require a little more research on your part to override correctly.
If you think about what you're asking - it will be clear you'll need to check, and add it yourself.
You're basically saying "If culture X doesn't contain the day name, add it" which translates to:
var date = DateTime.Now;
if(!date.ToLongDateString().Contains(date.ToString("dddd"))
//Add it
DateTime dt = new DateTime(2001, 5, 16);
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("nl-NL");
Debug.WriteLine(dt.ToLongDateString());
// output: woensdag 16 mei 2001
I suppose that other cultures might have formats that don't contain the day of week name, but the one you provided does - at least on my machine.
One thing to note, if you're going to check and add it yourself, are you sure that it should always be at the front of the string? In many cultures it is, but perhaps not all of them work that way. Also, what about the separator? Just a space is used here, but many use a comma and a space. Others could use something different.

Remove leading zero form month C#

I'm having trouble to remove the leading zero from a date I found this on the miscrosoft website.
DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August
Totally doesn't work here.
This is my code:
string date = '2013-04-01'
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.ToString("M");
Test is now 01 April
I just need it to be 4 in a string or int idc
Thanks!
Edit if I do:
billrunDate.ToString("(M)");
I get (4), but I dont need ()
EDIT 2:
Well this works
string test = billrunDate.ToString(" M ");
string testTwo = test.Trim();
Very very ugly
It's interpreting M as a standard date and time format for "month day pattern".
To interpret a single character pattern as a custom date and time pattern, just prefix it with %:
string test = billrunDate.ToString("%M");
One of my most referenced MSDN pages is the Custom Date & Time Format Strings page. You can use these as part of the formatting passed in to the ToString() method. If any of them are standard formatting patterns (as "M" is) and you want to use them along, you have to preface them with '%' or have a space before or after them in the format string (so use "%M", " M", or "M " instead of "M").
Relevant section:
"M"
The month, from 1 through 12.
"MM"
The month, from 01 through 12.
"MMM"
The abbreviated name of the month.
"MMMM"
The full name of the month.
You don't need to convert to string the date to retrieve the month number.
Just read the Month property of the DateTime class:
string date = "2013-04-01";
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.Month.ToString();

Categories