How to convert string "00:05:06,607" to DateTime? - c#

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

Related

Parsing timestamp containing special characters (quotes)

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!

DateTime Format provider for filepath

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.)

string date needs format

I have a string date like so:
var sDate = '3/3/2012'
It eventually goes into a DateTime.ParseExact(sDate, "MM/dd/yyyy")
and it fails because of the missing leading zeros.
What's the best way to add the leading zeros?
I know TryParse would have worked but can't refactor at the moment.
What's the best way to add the leading zeros?
Why would you do that? Just use ParseExact with the format it's actually got, which is M/d/yyyy.
The whole point of the format string is to let you declare the format of your data - not to make you change the format of your data.
Note that you can specify multiple patterns with this overload, so you could always pass in both M/d/yyyy and MM/dd/yyyy. I believe M/d/yyyy will work with zero-padded ones anyway though...

String Parsing a Time

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)

Parse DateTime in c# from strange format

if i have a datetime string in a weird format, such as YYYY##MM##DD HH**M**SS, how can i create a new datetime object base on that? i have read something about the datetimeformatinfoclass but not sure how to get it working..
You can use DateTime.ParseExact, or DateTime.TryParseExact for data which you're not confident in. For example:
using System;
class Test
{
static void Main()
{
string formatString = "yyyy'##'MM'##'dd' 'HH'*'mm'*'ss";
string sampleData = "2010##02##10 07*22*15";
Console.WriteLine(DateTime.ParseExact(sampleData,
formatString,
null));
}
}
The quotes in the format string aren't strictly necessary - this will work too:
string formatString = "yyyy##MM##dd HH*mm*ss";
However, using the quotes means you're being explicit that the characters between the quotes are to be used literally, and not understood as pattern characters - so if you changed "#" to "/" the version using quotes would definitely use "/" whereas the version without would use a culture-specific value.
The null in the call to ParseExact means "use the current culture" - in this case it's unlikely to make much difference, but a commonly useful alternative is CultureInfo.InvariantCulture.
It's unfortunate that there's no way of getting the BCL to parse the format string and retain the information; my own Noda Time project rectifies this situation, and I'm hoping it'll make parsing and formatting a lot faster - but it's far from production-ready at the moment.
You can use DateTime.ParseExact method and pass the format you need.

Categories

Resources