C# – Working with Spans of Time

As the beginning of the week, I want to show you ‘working with Spans of Time’

Let’s jump into topic as usual;

Create and Initialize new TimeSpans

//Days.Hours:Minutes:Seconds:Miliseconds

TimeSpan myTimeSpan =  TimeSpan.Parse("1.2:3:30.5");

DateTime myBirthday = DateTime.Parse("07/05/1997");

TimeSpan myAge = DateTime.Now.Subtract(myBirthday);

Get Individual Parts

myAge.Hours

myAge.Seconds

…… or get TOTAL elapsed time as double representing both of number of days / hour / etc.

AND fractional values representing “left overs”

myTimeSpan.TotalDays // double

myTimeSpan.TotalHours // double

 

More info taken from at microsoft.com

Converts the string representation of a time interval to its TimeSpan equivalent.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

public static TimeSpan Parse(
	string s
)

Parameters

s
Type: System.StringA string that specifies the time interval to convert.

Return Value

Type: System.TimeSpanA time interval that corresponds to s.

Exception Condition
ArgumentNullException

s is null.

FormatException

s has an invalid format.

OverflowException

s represents a number that is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue.

-or-

At least one of the days, hours, minutes, or seconds components is outside its valid range.

The s parameter contains a time interval specification in the form:

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

Elements in square brackets ([ and ]) are optional. One selection from the list of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required. The following table describes each element.

Element Description
ws Optional white space.
An optional minus sign, which indicates a negative TimeSpan.
d Days, ranging from 0 to 10675199.
. A culture-sensitive symbol that separates days from hours. The invariant format uses a period (“.”) character.
hh Hours, ranging from 0 to 23.
: The culture-sensitive time separator symbol. The invariant format uses a colon (“:”) character.
mm Minutes, ranging from 0 to 59.
ss Optional seconds, ranging from 0 to 59.
. A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (“.”) character.
ff Optional fractional seconds, consisting of one to seven decimal digits.

The components of s must collectively specify a time interval that is greater than or equal to TimeSpan.MinValue and less than or equal to TimeSpan.MaxValue.

The Parse(String) method tries to parse s by using each of the culture-specific formats for the current culture.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: