TimeSpan.ParseExact with ms - c#

Trying to parse the following time
string time = "12:25:1197";
TimeSpan t = TimeSpan.ParseExact(time, "HH.mm.ssff", CultureInfo.InvariantCulture);
What is wrong here?

First, you are using . as a separator, but your string uses :.
Second, that is a quite weird representation of seconds (which is a 60 based number) and milliseconds (which is a 100-based one), so you more likely have:
string time = "12:25:11.97" // remember the quotes
Which should be parsed with:
TimeSpan t = TimeSpan.ParseExact(time, "hh':'mm':'ss.ff", CultureInfo.InvariantCulture);
If you indeed have 12:25:1197 then you can use hh':'mm':'ssff, but that's indeed weird
Btw, if that's two digits for what you call ms, then that's hundreths of seconds, not milliseconds (which woulf be three digits)

This works:
TimeSpan t = TimeSpan.ParseExact(time, "hh\\:mm\\:ssff", CultureInfo.InvariantCulture);
Based on: https://msdn.microsoft.com/en-us/library/ee372287.aspx#Other

Related

C# TimeSpan.Milliseconds formated to 2 digits

I have a timer that I want to show minutes:seconds:hundreds of seconds.
Since C# timespan doesn't have a method to get hundreds but only milliseconds, I need to somehow format this.
TimeSpan ts = stopWatch.Elapsed;
currentTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, Math.Round(Convert.ToDecimal(ts.Milliseconds),2));
ClockTextBlock.Text = currentTime;
I've tried with Math.Round and nothing happened. The result is still anywhere from 1-3 digit, like this:
01:12:7
01:12:77
01:12:777
I want format to always be like
01:12:07
01:12:77
You need:
String.Format(#"Time : {0:mm\:ss\.ff}", ts)
Where "ts" is your TimeSpan object. You can also always extend this to include hours etc. The fff stuff is the number of significant digits of the second fractions
You can use a custom TimeSpan format string for that (here we're only displaying the first two digits of the milliseconds with ff, which represent the hundredths):
ClockTextBlock.Text = ts.ToString("mm\\:ss\\:ff");
You could set a DateTime type timezone and plus with Timespan span.
You would get a datetime and format it!
DateTime timezone = new DateTime(1, 1, 1);
TimeSpan span = stopWatch.Elapsed;
ClockTextBlock.Text=(timezone + span).ToString("mm:ss:ff");
Just put the format in toString and it simply will show you the desired format :)
Stopwatch s2 = new Stopwatch();
s2.Start();
Console.WriteLine(s2.Elapsed.ToString(#"hh\:mm\:ss"));
Since a millisecond is 1/1000 of a second, all you need to do is divide the milliseconds by 10 to get 100's of a second. If you are concerned about rounding, then just do it manually before the division.
int hundredths = (int)Math.Round((double)ts.Milliseconds / 10);
currentTime = String.Format("{0}:{1}:{2}", ts.Minutes.ToString(D2), ts.Seconds.ToString(D2), hundredths.ToString(D2);
ClockTextBlock.Text = currentTime;

How to store convert date time in int?

I need to store DateTime in int. So I tried below codes
Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));
or
Int64 twoday_date=Convert.ToInt64(System.DateTime.Today.ToString("dd-MM-yyyy"));
but its showing error:
Input string was not in a correct format.
Where is the error?
Just use DateTime.Ticks instead - there's absolutely no reason to start converting to and from strings here.
long ticks = DateTime.Today.Ticks;
// Later in the code when you need a DateTime again
DateTime dateTime = new DateTime(ticks);
Note that this will use the local date - if you're trying to retain a global timestamp, you should use DateTime.UtcNow instead of DateTime.Today.
If you really need int instead of long, you probably ought to translate and scale, e.g. to seconds since the Unix epoch.
You could either store the milliseconds from a certain point in time (that you define), or you could use a format such as yyyyMMddhhmmss (and fff if you want more precision).
The original question asks where is the error? within:
Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));
The ToString(...) method generates a string representation of the date time value. In this case its argument, the string "dd-MM-yyyy" gives the format of the string to be generated. So today that will generate the string "11-01-2014". The Int64.Parse(...) attempts to parse its argument string as an integer, but here it has a mix of digits and hyphens. Hence it throws an exception.
Understanding these sort of problems can be tricky. One technique is to break the statement into smaller pieces and understand each of them in turn. When the problem is resolved the corrected pieces can be assembled into a single statement if desired. In this case the statement could be split to be:
string s = DateTime.Today.ToString("dd-MM-yyyy");
Console.WriteLine("The date string is '{0}'", s);
Int64 n = Int64.Parse(s);
Then use either a debugger or the WriteLine shown to show the value in s. Note that the WriteLine encloses the displayed value of s in quotes so that the presence or absence of spaces, newlines and other unexpected characters can easily be detected.
// the local utc offset is +2:00
public class Program
{
public static void Main(string[] args)
{
// code executed in timezone GMT+2:00
long ticksUtc = DateTime.UtcNow.Ticks;
Console.WriteLine("{0:d}",ticksUtc);
DateTime _todayUtc = new DateTime(ticksUtc);
Console.WriteLine("{0}",_todayUtc);
// get local date time from Utc time
Console.WriteLine("{0}",_todayUtc.ToLocalTime());
Console.WriteLine();
long ticksLocal = DateTime.Now.Ticks;
Console.WriteLine("{0:d}",ticksLocal);
Console.WriteLine("{0:d}",ticksLocal-ticksUtc);
DateTime _todayLocal = new DateTime(ticksLocal);
Console.WriteLine("{0}",_todayLocal);
// get the utc time from _todaylocal time
Console.WriteLine("{0}",_todayLocal.ToUniversalTime());
}
}

Parsing times above 24 hours in C#

Suppose a time stamp (just time or date and time) where the time can roll over to the next day:
00:00:00 <- midnight
01:00:00 <- 1 AM
23:00:00 <- 11 PM
24:00:00 <- midnight, day + 1
25:00:00 <- 1 AM, day + 1
What would be a way to parse it easily into a C# DateTime that would perform the carry-over to the next day? In other words, "01:00:00" would become "0001-01-01 01:00:00" and "25:00:00" would become "0001-01-02 01:00:00".
EDIT:
I should mention that this fails miserably (i.e FormatException):
DateTime.ParseExact("0001-01-01 25:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Since you're trying to represent a period of time from an arbitrary point, rather than as a specific date, perhaps you would be better off using the System.TimeSpan class? This allows you to set values of more than 24 hours in the constructor, and can be used with DateTime objects like this:
System.TimeSpan timestamp = new System.TimeSpan(25, 0, 0);
System.DateTime parsedDateTime = new DateTime(0, 0, 0);
parsedDateTime = parsedDateTime.Add(timestamp);
Console.WriteLine(parsedDateTime.ToString("yyyy-MM-dd HH:mm:ss")); //Output as "0001-01-02 01:00:00"
NOTE: Code is untested.
EDIT: In terms of parsing the strings, I can't think of any basic .NET objects that parse strings with values greater than 23 for the hour (since 25 is an invalid hour of the day), but assuming that the format is consistent, you could create a very simple string parsing routine (or even a regular expression) to read the values individually, and load the constructor manually.
If you have an existing DateTime value you can add to, you can always use a TimeSpan:
string dt = "25:00:00";
int hours = int.Parse(dt.Split(':')[0]);
TimeSpan ts = TimeSpan.FromHours(hours);
TimeSpan.Parse() doesn't work directly in this case because it complains (fair enough!) about the 25 in the hour notation.
If you want to code it out... this should be a starting point:
string dateString = "0001-01-01 25:00:00";
string[] parts = dateString.Split(' '); //now have '0001-01-01' and '25:00:00'
string datePart = parts[0]; // '0001-01-01'
string[] timeParts = parts[1].Split(':'); //now have '25', '00', and '00
DateTime initialDate = DateTime.ParseExact(datePart, "yyyy-MM-dd", CultureInfo.InvariantCulture);//use the date as a starting point
//use the add methods to get your desired datetime
int hours = int.Parse(timeParts[0]);
int minutes = int.Parse(timeParts[1]);
int seconds = int.Parse(timeParts[2]);
DateTime resultDate = initialDate.AddHours(hours)
.AddMinutes(minutes)
.AddSeconds(seconds);
Of course, it makes assumptions that the input is formatted properly and is parsable, etc..
In addition, you could definitely use timespan instead of the individual add methods for hour, minute, second as some other answers are..
In case nobody points out an out-of-the-box answer, here is a neat ActionScript class I wrote to parse time inputs (human input)...
https://github.com/appcove/AppStruct/blob/master/Flex/AppStruct/src/AppStruct/TimeInput.as
It would be very simple to port this to C#, and you could tweak the 24 hour logic to result in #days, #hours, #minutes.
Good luck!
You are specifying an invalid date. So not only can you not parse it, you cannot store it!
How about a nice TimeSpan object instead? (It also has a Parse() method.)
Alternatively, use a sscanf()-type function like the one at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net to extract each number separate. (Best if you have no control over the string format being read.)

Convert a Time to a formatted string in C#

Time.ToString("0.0") shows up as a decimal "1.5" for instead of 1:30. How can I get it to display in a time format?
private void xTripSeventyMilesRadioButton_CheckedChanged(object sender, EventArgs e)
{
//calculation for the estimated time label
Time = Miles / SeventyMph;
this.xTripEstimateLabel.Visible = true;
this.xTripEstimateLabel.Text = "Driving at this speed the estimated travel time in hours is: " + Time.ToString("0.0") + " hrs";
}
Time.ToString("hh:mm")
Formats:
HH:mm = 01:22
hh:mm tt = 01:22 AM
H:mm = 1:22
h:mm tt = 1:22 AM
HH:mm:ss = 01:22:45
EDIT: Since now we know the time is a double change the code to (assuming you want hours and minutes):
// This will handle over 24 hours
TimeSpan ts= System.TimeSpan.FromHours(Time);
string.Format("{0}:{1}", System.Math.Truncate(ts.TotalHours).ToString(), ts.Minutes.ToString());
or
// Keep in mind this could be bad if you go over 24 hours
DateTime.MinValue.AddHours(Time).ToString("H:mm");
If Time is a System.Double, then System.TimeSpan.FromHours(Time).ToString();
I guess that Time is of type TimeSpan? In that case, the documentation of TimeSpan.ToString can help you, in particular the pages
Standard TimeSpan Format Strings and
Custom TimeSpan Format Strings.
If Time is a numeric data type, you can use TimeSpan.FromHours to convert it to a TimeSpan first.
(EDIT: TimeSpan format strings were introduced in .NET 4.)
Note that if you work in a 24-hour base, it's very important to use HH:mm and NOT hh:mm.
Sometimes I mistakenly write hh:mm, and then instead of "13:45" I get "01:45", and there's no way to know whether it's AM or PM (unless you use tt).
If time is float or double you'll have to.
System.Math.Truncate(Time) to get the hours
and then (Time - System.Math.Truncate(Time))* 60
to get the minutes.
Thanks for all of the responses guys and gals i used this DateTime.MinValue.AddHours(Time).ToString("H:mm");for my program since it was the easiest one to implement.
Create a timespan from you numeric variable:
TimeSpan ts = new TimeSpan(Math.Floor(Time), (Time - Math.Floor(Time))*60);
Then, use the ToString method.

Add or Sum of hours like 13:30+00:00:20=13:30:20 but how?

I want to add seconds (00:00:02) or minutes (00:00:20) on datetime value (may be stored string type) but how? Examples:
13:30+02:02:02= 15:32:02 ,
13:30+00:00:01= 13:30:01 ,
13:30+00:01:00=13:31:00 or 13:30 (not important)
Can you help me? I need your cool algorithm :) Thanks again...
myDateTimeVariable.Add(new TimeSpan(2,2,2));
If you choose to use the TimeSpan, be aware about the Days part:
TimeSpan t1 = TimeSpan.Parse("23:30");
TimeSpan t2 = TimeSpan.Parse("00:40:00");
TimeSpan t3 = t1.Add(t2);
Console.WriteLine(t3); // 1.00:10:00
With DateTime:
DateTime d1 = DateTime.Parse("23:30");
DateTime d2 = DateTime.Parse("00:40:00");
DateTime d3 = d1.Add(d2.TimeOfDay);
Console.WriteLine(d3.TimeOfDay); // 00:10:00
Adding two datetimes from strings:
var result = DateTime.Parse(firstDate) + DateTime.Parse(secondDate);
Adding a string time to a datetime:
var result = existingDateTime.Add(TimeSpan.Parse(stringTime);
Adding time as in your example:
var result = TimeSpan.Parse("12:30:22") + TimeSpan.Parse("11:20:22");
Finally, your example as dates (not tested!):
var result = DateTime.Parse("12:30:22") + DateTime.Parse("11:20:22");
Note that this is sloppy coding, but you get the idea. You need to verify somehow that the string is actually parseable.
Not really sure what you're after, but can you not just use the built in functions to C#'s DateTime object?
DateTime myDate = DateTime.Now;
myDate = myDate.AddHours(1);
myDate = myDate.AddMinutes(30);
myDate = myDate.AddSeconds(45);
The problem is more abstract. As already mentioned, in .NET there are two types - DateTime and TimeSpan. The DateTime type represents a specific point in time. It's not an interval of time. It's a specific location in all time since the birth of the Universe. Even if you set the year/month/day components to 0, it will still represent some absolute point in time. Not a length of time.
The TimeSpan on the other hand represents some interval. 1 minute, 2 days, whatever. It's not specified WHEN, just HOW LONG.
So if you were to subtract two DateTime objects you would get a TimeSpan object that specifies how much time there is between them. And if you add a TimeSpan to a DateTime you get another DateTime. But you can't add a DateTime to another DateTime - that would make no sense.
It sounds to me like you should be working with TimeSpans all the time, because you are dealing with lengths of time, not absolute points in time. If you get these lengths from your source as a DateTime then that's actually not correct, and you should convert them to TimeSpans somehow. The parsing method is one way that has been suggested, but you might also try to subtract zero DateTime from it. That might be faster and more culture-independant.
use the TimeSpan structure. you can add TimeSpans together, or you can add a TimeSpan to a DateTime to produce a new DateTime.
You should have a look at TimeSpan.Parse. This converts a string to a TimeSpan object. That way you can do stuff like
TimeSpan a = TimeSpan.Parse(timeStringA)+TimeSpan.Parse(TimeStringB);
To split a string like "00:00:20+00:01:00" look at string.split
stringA = timeSting.split('+')[0];
stringb = timeSting.split('+')[1];
return string.Format("{0}:{1}:{2}", mytimespan.Hours
+ (mytimespan.Days*24),mytimespan.Minutes,mytimespan.Seconds);
static void Main(string[] args)
{
String timeText = "3/23/2015 12:00:13 AM";
String timeText2 = "3/23/2015 1:45:03 AM";
DateTime time = Convert.ToDateTime(timeText);
string temp = time.ToString("HH:mm:ss");
DateTime time2 = Convert.ToDateTime(timeText2);
string temp2 = time2.ToString("HH:mm:ss");
TimeSpan t1 = TimeSpan.Parse(temp);
TimeSpan t2 = TimeSpan.Parse(temp2);
Console.Out.WriteLine(t1 + t2); // 01:45:16
Console.ReadLine();
}

Categories