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.
Related
I want to be able to parse strings of time (hours, minutes, seconds) where the hours run from 0 to 23, and where the preceding zero for one-digit hours is optional.
Examples of time strings that I want to be able to parse into valid DateTime objects:
212540
061525
94505
I am trying to use the C# method DateTime.ParseExact to manage the parsing, but I cannot for the life of it come up with a format string that can handle the "single-digit hour without preceding zero" scenario.
How should I specify the DateTime.ParseExact format string to sufficiently parse all examples above with the same line of code?
Inspired by the MSDN page on custom date and time formats, I have tried the following approaches:
DateTime.ParseExact(time_string, "Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "%Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "HHmmss", CultureInfo.InvariantCulture);
All these format strings work for the first two example cases above, but faced with a single-digit hour and no preceding zero, all formulations throw a FormatException.
You can insert delimiters between hours, minutes and seconds like this:
string timeString = "94505";
string formatedTimeString = Regex.Replace(str, #"\d{1,2}(?=(\d{2})+$)", "$&:");
var datetime = DateTime.ParseExact(formatedTimeString, "H:mm:ss", CultureInfo.InvariantCulture);
UPDATE:
I've found the cause of failure when parsing "94505" with format string "Hmmss":
What's happening is that H, m and s actually grabs two digits when they can, even if there won't be enough digits for the rest of the format. So the for example with the format Hmm and the digits 123, H would grab 12 and there would only be a 3 left. And mm requires two digits, so it fails.
So basically you have two options for handling the "single-digit hour without preceding zero" scenario:
Change time format: place hours to the end (for example, "ssmmH" or "mmssH") or use delimiters (for example, "H:mm:ss")
Modify the string like I've suggested earlier or like keyboardP has.
You could pad your input string if you know that you'll always have six characters.
string input = "94505";
if(input.Length < 6)
input = input.PadLeft(6, '0');
(Or use input.Length == 5 if you have other valid formats that are shorter).
What about using:
DateTime.ParseExact(time_string, "Hmmss", CultureInfo.InvariantCulture).ToString("HH:mm:ss")
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");.
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.
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);
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"