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!
Related
Context
The line JsonConvert.SerializeObject(DateTime.Now) gives the following result:
"2018-05-25T07:59:27.2175427+02:00"
However when I try to deserialize this JSON string to a DateTime with the line: JsonConvert.DeserializeObject<DateTime>("2018-05-25T07:59:27.2175427+02:00")
it gives an Newtonsoft.Json.JsonReaderException with the following message:
Unexpected character encountered while parsing value: 2. Path '', line 1, position 1.
What else I've tried so far
"2018-05-25T07:59:27"
causes the very same exception
Question
Having the datetime string in JSON serialized format, I would like to have a DateTime variable and the correct value in it. How can I accomplish this task?
As shown in the JSON standard, a JSON string literal must be quoted:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
Thus, to be valid JSON, your c# string literal must include the surrounding double quotes, like so:
var dateTime = JsonConvert.DeserializeObject<DateTime>("\"2018-05-25T07:59:27.2175427+02:00\"");
It's easy to confuse the outermost quotes, which are part of the c# language and delimit the string in your c# code but are not included in the string itself, with the inner quotes, which are part of the string literal itself.
Sample fiddle here.
The problem is that JsonConvert.DeserializeObject looks like it wants a JSON object rather than just any JSON value. (It's a shame that SerializeObject doesn't always produce an object, but...)
You can parse it like this:
DateTime dt = new JValue("2018-05-25T07:59:27.2175427+02:00").ToObject<DateTime>();
Or (equivalently? I'm not entirely sure):
DateTime dt = (DateTime) new JValue("2018-05-25T07:59:27.2175427+02:00");
There may be a better way of doing so, but that at least works.
Context
The line JsonConvert.SerializeObject(DateTime.Now) gives the following result:
"2018-05-25T07:59:27.2175427+02:00"
However when I try to deserialize this JSON string to a DateTime with the line: JsonConvert.DeserializeObject<DateTime>("2018-05-25T07:59:27.2175427+02:00")
it gives an Newtonsoft.Json.JsonReaderException with the following message:
Unexpected character encountered while parsing value: 2. Path '', line 1, position 1.
What else I've tried so far
"2018-05-25T07:59:27"
causes the very same exception
Question
Having the datetime string in JSON serialized format, I would like to have a DateTime variable and the correct value in it. How can I accomplish this task?
As shown in the JSON standard, a JSON string literal must be quoted:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
Thus, to be valid JSON, your c# string literal must include the surrounding double quotes, like so:
var dateTime = JsonConvert.DeserializeObject<DateTime>("\"2018-05-25T07:59:27.2175427+02:00\"");
It's easy to confuse the outermost quotes, which are part of the c# language and delimit the string in your c# code but are not included in the string itself, with the inner quotes, which are part of the string literal itself.
Sample fiddle here.
The problem is that JsonConvert.DeserializeObject looks like it wants a JSON object rather than just any JSON value. (It's a shame that SerializeObject doesn't always produce an object, but...)
You can parse it like this:
DateTime dt = new JValue("2018-05-25T07:59:27.2175427+02:00").ToObject<DateTime>();
Or (equivalently? I'm not entirely sure):
DateTime dt = (DateTime) new JValue("2018-05-25T07:59:27.2175427+02:00");
There may be a better way of doing so, but that at least works.
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."
var time = "00:05:06,607";
string pattern = "hh:mm:ss,fff";
DateTime.TryParseExact(time, pattern, null, DateTimeStyles.None, out parsedTime);
But the TryParseExact function returned me false. I also tried TryParse function like:
DateTime.TryParse(time, out parsedTime);
Also returned false until I change the time to "00:05:06.607". But my source date is lots of line like "hh:mm:ss,fff".
Anyone can help?
This is full project on github
https://github.com/DeronLee/PhoneBook/blob/master/subtitle/MakeSubtitle.cs
Try This
DateTime dateTime = DateTime.ParseExact(time, pattern ,CultureInfo.InvariantCulture);
The source data in my file is a Chinese subtitle file. I think maybe it used Chinese comma instead comma, so that's why My code didn't work but yours.
Ok. Finally. Not the comma. The space. I have to use trim() first.
It worked fine after I add trim function
I want to search for all possible dates in a string using Regex.
In my code i have this:
String dateSearchPattern = #"(?<Day>\d{2}).(?<Month>\d{2}).(?<Year>\d{4})|(?<Day>\d{2}).(?<Month>\d{2}).(?<Year>\d{2})";
// date format: dd.mm.yyyy or d.m.yyyy or dd.mm.yy or d.m.yy
String searchText = "20.03.2010.25.03.10";
Regex.Matches(searchText, dateSearchPattern); // the matching SHOULD give a count of 2
The above code gives only 1 match where it should give 2. Also i need to have a patthern when the date format is like d.m.yyyy or d.m.yy.
The pattern seems perfectly ok. It is giving two match. By any chance have you used the following line to check the count?
var match = Regex.Matches(searchText, dateSearchPattern);
Console.WriteLine(match.Count);
I used SD 3 on .Net 3.5 (w/o sp1) and your code is giving your desired result.
You can change your pattern to this:
"(?<Day>\d{1,2}).(?<Month>\d{1,2}).(?:(?<Year>\d{4})|(?<Year>\d{2}))"