TimeSpan.ParseExact giving error - c#

I created a TimeSpan this way
TimeSpan ts = new Timespan();
// Do some addition and subtraction on it
Then I am saving it to a file using this
string.Format("{0}:{1}:{2}:{3}", ts.Hours, ts.Minutes, ts.Seconds, ts.MilliSeconds);
Various values returned from it are like this
0:0:4:410
0:0:1:425
0:0:1:802
0:0:1:509
0:0:1:674
0:0:1:628
0:0:2:76
How to convert it back to TimeSpan.
I am using
TimeSpan.ParseExact("0:0:4:410", "h:m:s:fff", null);
but it is giving me error Input String is not in correct format.
Where am I wrong?

I believe you need to parse the colons, basically. I would also suggest using the invariant culture instead of the current thread culture:
var ts = TimeSpan.ParseExact("0:0:4:410", #"h\:m\:s\:fff",
CultureInfo.InvariantCulture);
From the documentation:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
I would also suggest using a format of h:mm:ss.fff instead - I believe this would be clearer than your current format. Note that you can use the format directly instead of your currently formatting approach:
const string TimeSpanFormat = #"h\:mm\:ss\.fff";
string text = ts.ToString(TimeSpanFormat, CultureInfo.InvariantCulture);
...
TimeSpan parsed = TimeSpan.ParseExact(text, TimeSpanFormat,
CultureInfo.InvariantCulture);

you will have to escape the colons : when you are doing the parse
TimeSpan.ParseExact("0:0:4:410", #"h\:m\:s\:fff", null)
The custom TimeSpan format specifiers do not include placeholder
separator symbols, such as the symbols that separate days from hours,
hours from minutes, or seconds from fractional seconds. Instead, these
symbols must be included in the custom format string as string
literals. For example, "dd.hh:mm" defines a period (.) as the
separator between days and hours, and a colon (:) as the separator
between hours and minutes.
was bitten some time back

Try this:
TimeSpan timeSpan = TimeSpan.ParseExact("0:0:4:410", #"h\:m\:s\:fff", null);

Related

How to change SQL Server time(7) format (hh:mm tt) in datagridview control c#

I checked this link
Format SQL Server 2012 Time(7) to "HH:mm"
but I want to change the format in C#.
Like this
dgvRoster.Columns[1].DefaultCellStyle = new DataGridViewCellStyle { Format = "hh:mm tt" };
This line of code works on datetime datatype of SQL Server.
I try to change datatype DateTime to time(7) and time(0) both but cause THIS EXCEPTION on those lines of code.
Stack Overflow Answer to a similar case in MySQL
.NET accepts the TIME datatype as System.TimeSpan not System.DateTime.
Here you are trying to assign custom DateTime format, that why you get
error as "Input string was not in a correct format".
You need to assign custom TimeSpan format, like
dataGridView1.Columns1.DefaultCellStyle.Format = #"hh:mm";
Check this link to know more about custom TimeSpan format
https://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx
By default, TimeSpan doesn't support 12hr time format.
You need to convert TimeSpan to DateTime object and specify any custom
DateTime format as you want.
From MSDN:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
You will have to use \\: instead of : for this.
The second issue is the tt which is not supported by TimeSpan
So, either you keep the datatype as DateTime, or change the format to Format = #"hh\:mm"

How convert TimeSpan to 24 hours and minutes String?

I use this code for converting Timespan to String (for ex: 14:53) :
myTimeSpan.ToString("hh:mm");
but this error occurs:
Input string was not in a correct format
What is the proper way to do this?
myTimeSpan.ToString(#"hh\:mm")
Custom TimeSpan Format Strings
The custom TimeSpan format specifiers do not include placeholder
separator symbols, such as the symbols that separate days from hours,
hours from minutes, or seconds from fractional seconds. Instead, these
symbols must be included in the custom format string as string
literals. For example, "dd.hh\:mm" defines a period (.) as the
separator between days and hours, and a colon (:) as the separator
between hours and minutes.
You need to use #"hh\:mm\" for TimeSpan. Timespan formatting is not exactly same as DateTime
myTimeSpan.ToString(#"hh\:mm");
Check out Msdn for more info
var result = string.Format("{0:D2}:{1:D2}", myTimeSpan.Hours, myTimeSpan.Minutes);
From TimeSpan.ToString Method (String)
TimeSpan t = new TimeSpan(14, 53, 0);
Console.WriteLine(t.ToString(#"hh\:mm"));
As an alternative you can use String.Format like;
Console.WriteLine(String.Format("{0}:{1}", t.Hours, t.Minutes));
Standard TimeSpan Format Strings
Custom TimeSpan Format Strings
Remember, TimeSpan.ToString(String) overload only avaiable for .NET 4 or higher.
Try this will work 100% !!
myTimeSpan.ToString(#"dd\.hh\:mm");.

Let user specify timer time?

I want the DispatcherTimer to read time values from the textbox : objTextBox.
I tried this code however it seems that TimeSpan is not compatible with strings or did I do anything wrong?
Error: Argument 1: cannot convert from 'string' to 'long'
Also; Does the Time have to look like this in textbox: 0, 0, 1 or 00:00:01?
Code here:
private void testing()
{
string theText = objTextBox.Text;
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(listjob3_Tick);
dispatcherTimer.Interval = new TimeSpan(theText);
dispatcherTimer.Start();
}
To convert string to TimeSpan, use TimeSpan.Parse(str)
To convert to a TimeSpan from a string you could leverage TimeSpan.Parse, but you'd have to conform to this format [ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws] where:
ws is Optional white space.
- is An optional minus sign, which indicates a negative TimeSpan.
d is Days, ranging from 0 to 10675199.
. is A culture-sensitive symbol that separates days from hours. The invariant format uses a period (".") character.
hh is Hours, ranging from 0 to 23.
: is The culture-sensitive time separator symbol. The invariant format uses a colon (":") character.
mm is Minutes, ranging from 0 to 59.
ss is Optional seconds, ranging from 0 to 59.
. is A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character.
ff is Optional fractional seconds, consisting of one to seven decimal digits.
so just converting days you could in fact use TimeSpan.Parse and just pass in the string - but if you wanted to convert minutes it would take some massaging of the input like this:
var input = string.Format("00:{0}", objTextBox.Text.PadLeft(2, '0'));
and so then you could issue var timeSpan = TimeSpan.Parse(input); because you've formatted it properly and the Parse will succeed. Another option is to turn minutes into days I guess, but that would require some floating point work and is really, IMO, not as good of an option.
I'm guessing your exception is here:
dispatcherTimer.Interval = new TimeSpan(theText);
Use this instead:
dispatcherTimer.Interval = new TimeSpan(Convert.ToInt64(theText));
#Sneakybastardd: have you read the TimeSpan documentation regarding constructor overloads? You'll note that none of them take string arguments: integer types are required.
After reading the documentation, you might find these TimeSpan methods useful:
Parse()
ParseExact()
TryParse()
With respect to format, See "Standard TimeSpan Format Strings" and "Custom TimeSpan Format Strings". Also do a little research on the various default TimeSpan formats for different cultures if that comes into play at all.

TimeSpan.TryParseExact not working

I'm trying to retrieve a timespan from a string, but TryParseExact is returning false (fail).
I can't see what I'm doing wrong, can you help? I've tried 2 versions of my line in the code, both do not work.
TimeSpan.TryParseExact("04:00:01","HH:mm:ss",CultureInfo.CurrentCulture, out aTime)
and
TimeSpan.TryParseExact("04:00:01","HH:mm:ss", null, out aTime)
EDIT:
both responses here are correct, I have the wrong format for my custom timespan format - the mistake I made is to assume that the custom formats for DateTime would work for TimeSpans, but they do not.
The problem is simply in the format string for the TimeSpan, you have specified "HH:mm:ss". The specifier HH (upper case) is not valid for timespan. You should use hh. Format strings are indeed case sensitive.
The colon character (:) also needs to be escaped, so use "hh\\:mm\\:ss", #"hh\:mm\:ss" or "hh':'mm':'ss". All three forms will have the same effect.
You can review a list of valid custom format strings for TimeSpan here. and the standard format strings for TimeSpan are here.
While HH is valid for DateTime and DateTimeOffset where it represents the 24 hour clock and lower case hh represents a 12 hour clock, For TimeSpan - the hours component is always based on 24 hours. You would think that the HH format would be the one chosen, for uniformity, but nope - it's hh.
It's probably should get mentioned that you need to escape the colon character.
TryParseExact("04:00:01", "HH\\:mm\\:ss" ...
The string format which you are passing is wrong.
var res=TimeSpan.TryParseExact("04:00:01", "g", CultureInfo.CurrentCulture, out aTime);
g- General short format and is culture sensitive.
More on this here Standard Timespan Format Strings
Maybe you were using multiple formats.
public const string TimeFormat1 = "hh\\:mm";
public const string TimeFormat2 = "hh\\:mm:\\ss";
var parsed = TimeSpan.TryParseExact(time, new [] { TimeFormat1, TimeFormat2 }, CultureInfo.CurrentCulture, out TimeSpan ts1);
// parsed is always false
You might have thought you escaped your colon; but didn't, actually...
This "hh\\:mm:\\ss" won't work.
Using TimeFormat2 in ParseExact throws a FormatException...
You meant to use this "hh\\:mm\\:ss" instead.

C# + Format TimeSpan

I am trying to format a TimeSpan element in the format of "[minutes]:[seconds]". In this format, 2 minutes and 8 seconds would look like "02:08". I have tried a variety of options with String.Format and the ToString methods, but I get a FormatException. This is what I'm currently trying:
DateTime startTime = DateTime.Now;
// Do Stuff
TimeSpan duration = DateTime.Now.Subtract(startTime);
Console.WriteLine("[paragraph of information] Total Duration: " + duration.ToString("mm:ss"));
What am I doing wrong? How do I format a TimeSpan element using my desired format?
NOTE: This answer applies to .NET 4.0 only.
The colon character is a literal and needs to be wrapped in single quotes:
duration.ToString("mm':'ss")
From the MSDN documentation:
The custom TimeSpan format specifiers
do not include placeholder separator
symbols, such as the symbols that
separate days from hours, hours from
minutes, or seconds from fractional
seconds. Instead, these symbols must
be included in the custom format
string as string literals.
Try this:
Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);
Custom formatting of System.TimeSpan was added in .Net 4, so you can now do the following:
string.Format("{0:mm\\:ss}", myTimeSpan);
(UPDATE) and here is an example using C# 6 string interpolation:
$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15
In short you now need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).
This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." charecters in a format string:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
For some mysterious reason TimeSpan never got the ToString() overloads that support formatting until .NET 4.0. For earlier releases, as long as it is positive, you can hijack DateTime.ToString():
TimeSpan ts = new TimeSpan(0, 2, 8);
string s = new DateTime(ts.Ticks).ToString("mm:ss");
The date and time format strings only apply to DateTime and DateTimeOffset. Yo can use a normal format string, though:
string.Format("{0}:{1:00}", Math.Truncate(duration.TotalMinutes), duration.Seconds)
Note that using TotalMinutes here ensures that the result is still correct when it took longer than 60 minutes.
Try this:
DateTime startTime = DateTime.Now;
// Do Stuff
TimeSpan duration = DateTime.Now.Subtract(startTime);
Console.WriteLine("[paragraph of information] Total Duration: " + duration.Minutes.ToString("00") + ":" + duration.Seconds.ToString("00"));
Based on this MSDN page describing the ToString method of TimeSpan, I'm somewhat surprised that you can even compile the code above. TimeSpan doesn't have a ToString() overload that accepts only one string.
The article also shows a function you can coyp and use for formatting a TimeSpan.
you could always do:
string.Format("{0}:{1}", duration.Minutes, duration.Seconds);
You can use the below code.
TimeSpan tSpan = TimeSpan.FromSeconds(allTotalInMinutes);
string tTime = string.Format("{1:D2}:{2:D2}", tSpan.Minutes, tSpan.Seconds);
It will show ie 34:45 format.
Hope it will help you.
TimeSpan t = TimeSpan.Parse("13:45:43");
Console.WriteLine(#"Timespan is {0}", String.Format(#"{0:yy\:MM\:dd\:hh\:mm\:ss}", t));

Categories

Resources