I am trying to find the file that has the highest date in a single directory. The problem is that the dates are attached to filenames. I am using the following code to try to pull the max date but am running into trouble with the ParseExact.
//Gather all of the files in the local directory
var files = Directory.EnumerateFiles(r.getLeadLocalFile());
returnDateTime = files.Max(f => DateTime.ParseExact(f, "MMddyyXXXX.csv", CultureInfo.InvariantCulture));
I continue to get the following error:
String was not recognized as a valid DateTime.
I can tell that the value of the file path is being passed in because the value of 'f' is below:
\\\\vamarnas02\\users\\meggleston\\User Files\\Leads\\110716ENH9.csv
The value of ENH9 can change depending on the file.
How can I get the DateTime from my filename?
Here's another approach. No need to split out anything. But one bad filename (as with your current approach) will ruin it:
//Gather all of the files in the local directory
var files = new DirectoryInfo(r.getLeadLocalFile()).GetFiles("*.csv");
returnDateTime = files.Max(f => DateTime.ParseExact(f.Name.Substring(0, 6), "MMddyy", CultureInfo.InvariantCulture));
You need to split out the date text before parsing. The following code snippet should help.
Assume the variable f is the filename.
DateTime.ParseExact(f.Substring( f.LastIndexOf("\\") + 1, 6), "MMddyy", CultureInfo.InvariantCulture);
Do you really need to use ParseExact here? Because it seems that you just need to get Int32 values and compare them afterwards.
So another approach: you can extract your date parts with some regex, from the path provided. For example you can use this one:
\\\d{6} // 2 slashes and 6 digits. I'm not an expert in regex, but seems that this one is enough for your task.
And trim the \\ part afterwards. So something like this in the loop:
private string ExtractDateFromFilename(string filename) {
var m = Regex.Match(filename, #"\\\d{6}");
if (!string.IsNullOrEmpty(m.Value))
return m.Value.Substring(1);
return "";
}
Try only passing the filename "110716ENH9.csv" instead of the full path of the file.
From MSDN DateTime.ParseExact Documentation:
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
From what you've provided, your format does not match exactly.
--
Only pass the first 6 characters of the filename to the ParseExact function and amend your format to be "MMddyy."
Related
So, the other day I ran into a problem when trying to parse a timestamp which was wrapped in quotes, it looked like this in the file I was reading:
"2018-04-09"
A C# string with this content:
var dt = "\"2018-04-09\""
I wanted to use DateTime.TryParseExact() to convert the string into a .net DateTime object, without stripping the chars from the string (don't ask why, it's not relevant), but finding a working format string turned out to be tricky.
I read the docs. I googled. Searched StackOverflow. No success.
What format would allow me to parse this timestamp to a DateTime object?
So - the solution, handed to me by a colleague:
var format = "\\\"yyyy-MM-dd\\\"";
If I understand this correctly, the format string is expected to contain a \ which is later resolved to escape the " inside ParseExact(). The first \ escapes the second, the third escapes ", leading to the character sequence \" as part of the format string which is then processed somewhere down the line.
The following works:
var dts = "\"2018-04-09\"";
var format = "\\\"yyyy-MM-dd\\\"";
var dt = DateTime.ParseExact(dts, format, null);
I hope this helps someone!
I have this path which saves a excel sheet on the basis of date and time.
It is Showing
System.NotSupportedException
What is the correct Format ?
string strpath = Server.MapPath("~/SavedFolder/"+ username+ "/"+DateTime.Now+".xlsx/");
Your problem (after removing the final slash) is caused by the conversion of DateTime.Now to a string using your locale settings. This produces a string like this
h:\temp\08/06/2016 09:19:42.txt
and this string contains invalid chars as you can see calling Path.GetInvalidFileNameChars (the slash, backslash are confused as part of a folder name, while the colon is simply not a valid char for a file)
You can use the formatting capabilities of NET to prepare your file name in this way
filename= DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
string strpath = Server.MapPath("~/SavedFolder/"+ username+ "/"+ filename + ".xlsx");
Usually, when I need to tag my files with a datetime part, I put the date parts in the order of year, month, day, hour, minute, second to get an easy way to see them sorted in any file explorer that supports ordering by name.
Check the output of DateTime.Now.ToString() (which been called in this case), it seems that it contains characters which is not allowed path of file name.
string strpath = Server.MapPath("~/SavedFolder/"+ username+ "/"+DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") +".xlsx");
I have a file-path that's been created from DateTime stamp:
"C:\\Logs\\Tests\\2015\\Mar\\24\\13_32_09\"
Now I am trying to convert my file-path back to DateTime object.
With Regex I can easily remove "C:\\Logs\\Tests\", but now I am assume I need to provide implementation of IFormtProvider to convert 2015\\Mar\\24\\13_32_09\ into a DateTime object, but I haven't come along any similar example of how that's usually done.
Any example, may not be particular solution to my answer, would be helpful.
Thanks
You can use DateTime.ParseExact like:
DateTime dt = DateTime.ParseExact("2015\\Mar\\24\\13_32_09\\",
#"yyyy\\MMM\\dd\\HH_mm_ss\\",
CultureInfo.InvariantCulture);
No, you don't need to create an IFormatProvider at all. The invariant culture is fine for this (assuming the month name is always in English). You can just use DateTime.ParseExact, passing in the appropriate custom format string (quoting the literal characters, either with apostrophes around them or backslashes before them):
var dateTime = DateTime.ParseExact(
text,
#"yyyy'\'MMM'\'dd'\'HH'_'mm'_'ss'\'",
CultureInfo.InvariantCulture);
Note that this assumes the path really does use backslashes... it won't work on Unix as-is. (You might want to canonicalize the directory separators first.)
Hi for some reason I cant do a string comparison on a date? Take for example:
public List<HireDate> GetHireDate(string anything)
{
List<HireDate> hiredate = hiredates.Where(n =>
string.Equals(n.HireFromDate, anything, StringComparison.CurrentCultureIgnoreCase)
).ToList();
return hiredate;
}
It simply wont work? if I type into a textbox 13/07/2012 which is how its stored it returns a 404 not found???
The output looks like this from a generic list/get request:
<ArrayOfHireDate>
<HireDate>
<HireFromDate>13/07/2012</HireFromDate>
<HireToDate>28/07/2012</HireToDate>
<NumberOfDaysHired>15</NumberOfDaysHired>
</HireDate>
</ArrayOfHireDate>
Is there another way to find a string with a forward slash in it? For instance using / in any of web string comparers does not work it will always throw a 404 not found?
Two things:
1) To put a string in another string, the most common way to do this is using String.Format. That method takes a format string (such as "Date: {0} Time: {1}") and a bunch of arguments. Each occurrence of {0} in the string is replaced by the first argument, {1} by the second, etc.. There are additional options to format the arguments in the string, see for more information the MSDN page on String.Format.
2) If you have an URL and you get a 404 in your application, first verify that the syntax of the URL is correct. Manually try the URL you create in your program directly in your browser, and if it does not work, find out what syntax is actually used to provide the arguments. For example, it might be that a date must be formatted as 13-07-2012 instead of 13/07/2012 for it to work. If so, you can probably solve this by choosing the appropriate CultureInfo.
For any DateTime date object, to format it has a short date using any CultureInfo you want, use an overload of ToString and specify d as the format. For example, using the invariant culture:
var str = date.ToString("d", CultureInfo.InvariantCulture);
Other format strings can be found here.
I need to obtain a time in the format of "07:30 am" (not case-sensitive). I'm reading a file which has this in the format "07:30am". Eventually I will be constructing a DateTime from this, so I just need to get this back with a space before the am/pm part.
I can detect the occurrence of the a or p using this:
if(startString.IndexOfAny("ap".ToCharArray()) != -1)
{
}
What's the best ways to do this? I'm guessing I will end up with two strings that can be concatenated with a space? Can Split be used with the above snippet to achieve this?
UPDATE:
I need to end up with a space in the DateTime between the minutes and the AM/PM and I do not want to use regular expressions. So far, nothing I've tried here gives me that...
The actual input I have to handle is in this format:
RecDate: "04/30/2012"
RecTime: "05:30am"
I need to create a new DateTime object from these with a space before the am/pm part.
You have two easy choices:
Use RegEx to fix the formatting:
string newTime = Regex.Replace(startString, #"(?<=[01]\d:[0-5]\d)(?=[ap]m)", " ");
Use DateTime.ParseExact to just import the time as-is:
DateTime newValue = DateTime.ParseExact(
startString,
"hh:mmtt",
CultureInfo.InvariantCulture);
I'm partial to the second approach.
You need to use the Invariant Culture because there is no separator defined between the mm and tt in the format.
Why you are not using Regular Expression for this? ( http://msdn.microsoft.com/de-de/library/system.text.regularexpressions.regex(v=vs.80).aspx ) should be an easy thing for a Regex-Wizard (which I'm not)