How convert TimeSpan to 24 hours and minutes String? - c#

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

Related

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.

TimeSpan.ParseExact giving error

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

remove seconds from timespan using c#

I want to remove the seconds from timespan using c#
My code is here:
TimeSpan lateaftertime = new TimeSpan();
lateaftertime = lateafter - Convert.ToDateTime(intime) ;
It returns the value 00:10:00
But i want the below output :00:10 only not seconds field :00.
Well you can simply do as
string.Format("{0}:{1}", ts.Hours,ts.Minutes) // it would display 2:5
EDIT
to get it properly formatted use
string.Format("{0:00}:{1:00}", ts.Hours,ts.Minutes) // it should display 02:05
Note that a TimeSpan does not have a format. It's stored in some internal representation¹ which does not resemble 00:10:00 at all.
The usual format hh:mm:ss is only produced when the TimeSpan is converted into a String, either explicitly or implicitly. Thus, the conversion is the point where you need to do something. The code example in your question is "too early" -- at this point, the TimeSpan is still of type TimeSpan.
To modify the conversion to String, you can either use String.Format, as suggested in V4Vendetta's answer, or you can use a custom format string for TimeSpan.ToString (available with .NET 4):
string formattedTimespan = ts.ToString("hh\\:mm");
Note that this format string has the following drawbacks:
If the TimeSpan spans more than 24 hours, it will only display the number of whole hours in the time interval that aren't part of a full day.
Example: new TimeSpan(26, 0, 0).ToString("hh\\:mm") yields 02:00. This can be fixed by adding the d custom format specifier.
Custom TimeSpan format specifiers don't support including a sign symbol, so you won't be able to differentiate between negative and positive time intervals.
Example: new TimeSpan(-2, 0, 0).ToString("hh\\:mm") yields 02:00.
¹ TimeSpan is just a thin wrapper around a 64-bit integer containing the number of ticks (10,000 ticks = 1 millisecond). Thus, 00:10:00 will be stored as the number 6,000,000,000.
TimeSpan newTimeSpan = new TimeSpan(timeSpan.Hours, timeSpan.Minutes, 0);
Since there can be more than hours and minutes in a timespan string representation, the most reliable code for removing just the seconds and nothing else would be something like this:
var text = TimeSpan.FromDays(100).ToString(); // "100.00:00:00"
var index = text.LastIndexOf(':');
text = text.Substring(0, index); // "100.00:00"

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