I have several strings in the format below:
"1:15"
":45"
"1:30:45"
I need them converted to a TimeSpan, but when I TimeSpan.Parse some of them (the first one, for example) it returns it as 1 hour and 15 minutes, where i would want it to be 1 minute and 15 seconds.
Any advice would be greatly appreciated!
You could use an overload of TimeSpan.ParseExact that allows you to specify an array of exact format specifiers.
var formats = new string[] {#"m\:s", #"\:s", ...};
var timeSpace = TimeSpan.ParseExact(input, formats, CultureInfo.CurrentCulture);
Note that ParseExact was introduced in .Net 4
The parameter string needs to be in the specific form specified below:
[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
So "1:15" will be treated as hh:mm. If you are passing 1 min 15 seconds, you need to reformat your parameter string to be "00:01:15". You can simply split your string to corresponding days, hour, min, ss variables and use those to assign your TimeSpan object.
MSDN has good documentation here:
http://msdn.microsoft.com/en-us/library/se73z7b9.aspx
Related
I have a time span string like this: 20 min 49 sec
I would like to parse it TimeSpan instance, however I'm having bad time with it.
From the docs, it states that days and hours properties have to be set, but in my case I don't have them and I'd like to know if it's possible to make create such format where I can omit those values.
To parse that exact string, you'd use this expression:
TimeSpan.ParseExact(input, #"%m' min '%s' sec'", CultureInfo.InvariantCulture)
Basically, you treat every text other than where the numbers are as literal delimiters, specified using the 'xxx' syntax.
If you think you might need to handle both min and mins as well as sec and secs, you need to use the overload with multiple formats:
string[] formats = new[]
{
"%m' min '%s' sec'",
"%m' mins '%s' sec'",
"%m' min '%s' secs'",
"%m' mins '%s' secs'"
};
TimeSpan.ParseExact(input, formats, CultureInfo.InvariantCulture)
And contrary to what you think the documentation states, you don't have to specify days or hours at all, this is perfectly legal:
TimeSpan ts = TimeSpan.FromMilliseconds(45);
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 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"
I'm trying to find the appropriate format string to parse (exact) the following types of dates:
1-01-01T00:00:00+00:00 - 1 January of 0001
2011-12-14T15:53:40+00:00 - 14 December of 2011
So the year length seems to be variable (1-4 characters).
The format sting I currently use to parse exact is:
c_DateTimeFormatString = "yyyy-MM-ddTHH':'mm':'sszzz"
Obviously this only matches the second string. The first one poped up today. Now we have to match that as well.
Is there a format string to achieve this?
UPDATE #1
I added the actual dates in clear text after the input date strings.
UPDATE #2
Parse exact has an overload that allows for multiple format strings to be passed in. This seems to be the right way.
So the first try was to use:
DateTime.ParseExact("1-01-01T00:00:00+00:00 ", new[] { "yyyy-MM-ddTHH':'mm':'sszzz", "yyy-MM-ddTHH':'mm':'sszzz", "yy-MM-ddTHH':'mm':'sszzz", "y-MM-ddTHH':'mm':'sszzz" }, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal)
But sadly this does ont give the correct result, the first date string is parsed as:
01.01.2001
rather than
01.01.0001
So the question now is what is the correct parsing string to parse year one which is represented with only one digit?
Updated based on comment:
string y = "yyyy-MM-ddTHH':'mm':'sszzz";
string testDate = "1-01-05T00:00:00+00:00".PadLeft(25, '0');
Console.WriteLine(DateTime.ParseExact(testDate, y, CultureInfo.InvariantCulture));
testDate = "2011-12-14T15:53:40+00:00".PadLeft(25, '0');
Console.WriteLine(DateTime.ParseExact(testDate, y, CultureInfo.InvariantCulture));
The output is:
1/5/0001 00:00:00
12/14/2011 15:53:40
You can use an overload of ParseExact to match multiple formats, I believe.
See MSDN.
If the input formats are not all exactly the same, you'll need either to stop using parse exact, or to call it with different format arguments depending on the format of the input data.
I don't believe you need to match a year from 1 to 4 characters but 2 or 4 characters.
For this example
1-01-05T00:00:00+00:00
you would need something like
d-MM-yyTHH':'mm':'sszzz
Try padding your string so that the year is 4 digits long. You should probably add 2, 20 or 201 and not just 0's.
Since you know that you have to support multiple formats, I suggest that you use the TryParseExact method.
If it fails to parse using one format (i.e. it returns false), then try the next format.