How can I parse a TimeSpan with milliseconds included? - c#

I have an application that reads 'timed' data out of a file; currently, my input is something like this:
-- EDIT -- I have found an actual case where this fails.
0:0:1:934 > >> GOOD MORNING.<br>
But I seem to be having some trouble parsing this into a valid TimeSpan.
I would appreciate if someone could point me in the right direction, as not many offerings that I've found thus far provided much in the way of solving the problem.
As my code stands;
String StoredTime = ArchiveLine.Split('>')[0].TrimEnd();
String StoredFrame = ArchiveLine.Substring(ArchiveLine.IndexOf('>')+1).TrimStart();
TimeSpan FrameTime = TimeSpan.Parse(StoredTime, DateTimeFormatInfo.InvariantInfo);
And it throws a format exception.
Thanks.

It may be a localisation issue. Some cultures use a comma instead of a period as the decimal point. Try:
TimeSpan FrameTime = TimeSpan.Parse(StoredTime, DateTimeFormatInfo.InvariantInfo);

The problem here is that (I) referenced the wrong portion of my line in the Parse method...

Related

How to extract date from datetime in C# without converting it into string?

I am trying to extract date from date time field but in C# it is not helping me to do it without converting it to string.
This is my class:
public class Student_Info
{
public String Student_Name;
public DateTime DateofBirth;
}
Student_Info student = new Student_Info();
student.Student_Name = "XYZ";
student.DateofBirth = Convert.ToDateTime("2019-01-01");
MessageBox.Show(student.Student_Name + "" + student.DateofBirth);
This is how I am setting the value.
My expected result is XYZ 2019-01-01
But I am getting XYZ 1/1/2019 12:00:00 AM
Need Help?
Thanks in Advance
The DateTime struct always has a time component. There is a Date property that will mostly do what you asked, but even that has an implied time of midnight.
However, while the question text says this:
without converting it into string?
the code sample IS implicitly converting to a string:
MessageBox.Show(student.Student_Name + "" + student.DateofBirth);
In which case there are a number of options:
student.DateofBirth.ToShortDateString()
student.DateofBirth.ToString("d")
student.DateofBirth.ToString("d", CultureInfo.CreateSpecificCulture("de-DE")) //German format. You can put any culture here you need.
student.DateofBirth.ToString("d", CultureInfo.InvariantCulture)
student.DateofBrith.ToString("yyyy-MM-dd")
Just be careful here, because some of those rely on the operating system's date format, and users can configure that to do really weird stuff if they really want to.
You can also use any of these right in the MessageBox string:
MessageBox.Show($"{student.Student_Name}{student.DateofBirth:yyyy-MM-dd}");
MessageBox.Show(string.Format(CultureInfo.InvariantCulture, "{0}{1:d}", student.Student_Name, student.DateofBirth));
Finally, I get a little scared whenever I see someone wanting to create a date string resembling the ISO-8601 date format, as is the case here. There are plenty of legitimate reasons to do this. However, there is one common reason people want to do this that also happens to be very bad: SQL. If you're doing this so you can include it in an SQL command string, you're almost certainly doing something very wrong, and you need to take a step back and research parameterized queries before doing anything else.
Try this
MessageBox.Show(student.Student_Name + "" + student.DateofBirth.ToString("yyyy-MM-dd"));

Subtraction using DateTime retrieved from database giving strange results

I am having some trouble doing some DateTime subtractions with a time that I have received from a MySQL database. All of the non-UTC times are in the American format.
This is the time I have received (I retrieve it from the database using a Ruby on Rails app), which comes in the form of a string:
2017-04-10T15:00:00.000Z
I then parse the string to convert it to a DateTime and do a debug of the regular DateTime (without the offset):
start_time = DateTimeOffset.Parse(event_time[2]);
Debug.Log(start_time.DateTime);
Which then shows the following:
4/10/2017 3:00:00 PM
This appears similar to the format I usually use (i.e. M/dd/yyy h/mm/ss tt), so I do a quick comparison with the current time to check exactly how far off I am from it (for reference, DateTime.Now = 4/10/2017 12:46:26 AM when I ran this code last):
TimeSpan tmp;
tmp = (start_time.DateTime).Subtract(DateTime.Now);
Debug.Log(tmp)
However, this gives me the following result:
-736428.00:46:22.2744445
Doing such an operation with the following gives me a normal result:
DateTime tmp2;
TimeSpan tmp3;
tmp2 = DateTime.Now.Add(new TimeSpan(0, 0, 360));
tmp3 = tmp2.Subtract(DateTime.Now)
Debug.Log(tmp2);
Debug.Log(tmp3);
Normal Result:
4/10/2017 12:52:26 AM
00:06:00
Is there something wrong with how I have handled the time I got from my database? I can not seem to get a normal result no matter what I try.
I tried it in fiddler with the same input and syntax and I'm getting the expected result. Check how Debug.Log internally handles the TimeSpan object. Also try to print the values (difference in hour/min/seconds) before you pass it to Debug.Log to check if it reports correct result.
I found a solution to my issue (kind of?).
I also must apologize since I did not fully describe how I was using the code that I originally posted.
It turns out the issue was that I was that I was attempting to perform the DateTime subtraction in another script (I am doing this all within Unity, like I mentioned earlier).
For example, this was the code giving me the erroneous output in the script Buttonscript.cs:
TimeSpan tmpButtonController;
tmpButtonController = HighscoreController.GetComponent<HSController>().start_time.DateTime.Subtract(DateTime.Now);
Debug.Log(tmpButtonController);
But if I do the same thing, but inside the same script in which I parse the string (HSController.cs), everything is fine:
TimeSpan tmpHSController;
tmpHSController = start_time.DateTime.Subtract(DateTime.Now);
Debug.Log(tmpHSController);
Again, not exactly sure why this was was happening, but I have resolved/have a workaround for the issue now. If anyone knows why this error was occurring in the first place, please let me know!
Thank you everyone for your input!

Input string not in correct format to parse into DateTime

I am facing problem while converting DataTime into Time on 12 hour clock machine. Following code works fine on 24 Hour clock machine.
(new DisplayReminder(_name, _displayText, _snoozTime, TimeSpan.Parse(_startTime.ToShortTimeString(), CultureInfo.InvariantCulture))).Show();
TimeSpan.Parse(_startTime.ToShortTimeString() throws exeception that input string not in correct format, here I am trying to get time part from DateTime value _startDate
Any suggestion or solution on this problem.
It's not clear what you're trying to do, but just getting the time of day shouldn't involve string conversions:
TimeSpan time = _stateTime.TimeOfDay;
I'd strongly advise you to avoid string conversions unless they're inherently part of what you're trying to achieve.
Personally I don't like using TimeSpan as a time of day anyway, but that's the BCL for you. You might want to also look into my Noda Time library which has a clearer separation of various date/time concepts.
Try this:
TimeSpan.ParseExact(
_startTime.ToString("hh:mm:ss"), "hh:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
it will format your date to same format as TimeSpan.ParseExact accepts, so it will run on any machine (I assume that _startTime is DateTime)
Try
startTime.TimeOfDay.ToString()
I am pretty sure that it works fine when 24H but crushes in 12H system, BECAUSE of the "PM" "AM" part ! get rid of it you'll be safe
11:54:33 PM and 23:54:33 are VERY different in terms of handling
EDIT
it might be not the best solution but it works if you cut the last indexes of the string:
int index = _StartTime.IndexOf("M");
if (index >= 0)
{
_StartTime = _StartTime.Substring(0, index-1);
switch (_StartTime.IndexOf("P"))
case : -1
_StartTime = _StartTime.Substring(0,_StartTime.Length);
break;
default:
string hours = _startTime.Substring(_StartTime.Length-8,2);
int H = Convert.ToInt32(hours);
H += 12;
string result = _StartTime.Substring(0, _StartTime.Length-8)+ Convert.ToString(H)+_startTime.Substring(_StartTime.Length-6);
_StartTime = result;
break;
}
this will throw AM/PM away, you can use the same previous code after this
SECOND EDIT
it's the most horrible solution but it works ;)

datetime.TryParseExact with different formats of values

I have a json string that contains the values for a datetime and a parsing mechanism that looks like this:
if (DateTime.TryParseExact(TheUserTimeString, "M.d.yyyy.HH.mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out TheUserTime))
{
TheObject.UserDateTime = TheUserTime;
}
The string TheUserTimeString is generated on the client. It can be 12.20.2011.13.21 and the code works fine but when it's 12.20.2011.13.2 the code breaks because the minutes are in one digit. And when the month is also in one digit... who knows.
What would be a better way to rewrite this parsing code so that the string gets parsed correctly every time.
Thanks for your suggestions.
Use the string "M.d.yyyy.HH.m", a single m denotes minutes without the leading 0. Source.
Your DateTime format string just needs to be: "M.d.yyyy.H.m".
This allows for months, days, hours and minutes to be expressed as single digit values.
See here for the MSDN page documenting the valid formats of this string for further information.

How to Convert date into MM/DD/YY format in C#

In My Asp.net webpage I need to display today's date into one of the textbox , so in my form load I wrote the following code
textbox1.text = System.DateTime.Today.ToShortDateString();
this line is giving me date like 1/7/09 but I want date like 01/07/09 , Is there anyway I can conver this date into mm/dd/yy format in C#?
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...
To resolve that problem i do someting like this:
IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
return date.ToString("MM/dd/yy", yyyymmddFormat);
Have you tried the following?:
textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");
Be aware that 2 digit years could be bad in the future...
Look into using the ToString() method with a specified format.
See, here you can get only date by passing a format string.
You can get a different date format as per your requirement as given below for current date:
DateTime.Now.ToString("M/d/yyyy");
Result : "9/1/2016"
DateTime.Now.ToString("M-d-yyyy");
Result : "9-1-2016"
DateTime.Now.ToString("yyyy-MM-dd");
Result : "2016-09-01"
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
Result : "2016-09-01 09:20:10"
For more details take a look at MSDN reference for Custom Date and Time Format Strings

Categories

Resources