Parse string to TimeSpan
In this chapter you will learn:
- Use the Parse() method to convert strings to TimeSpan instances: 8:10:30
- Use the Parse() method to convert strings to TimeSpan instances: 1.8:10:30.1234567
- Converts string to TimeSpan by using the specified format and culture-specific format information
Parse string
using System;//j a v a 2s . co m
class MainClas
{
public static void Main()
{
TimeSpan myTimeSpan11 = TimeSpan.Parse("8:10:30");
Console.WriteLine("TimeSpan.Parse(\"8:10:30\") = " + myTimeSpan11);
}
}
The code above generates the following result.
Parse string with milliseconds
using System;// ja v a 2 s . c o m
class MainClas
{
public static void Main()
{
TimeSpan myTimeSpan12 = TimeSpan.Parse("1.8:10:30.1234567");
Console.WriteLine("TimeSpan.Parse(\"1.8:10:30.1234567\") = " + myTimeSpan12);
}
}
The code above generates the following result.
Parse string with culture information
using System;// jav a2 s . c o m
using System.Globalization;
public class Example
{
public static void Main()
{
string intervalString, format;
TimeSpan interval;
CultureInfo culture;
// Parse hour:minute value with "g" specifier current culture.
intervalString = "17:14";
format = "g";
culture = CultureInfo.CurrentCulture;
try {
interval = TimeSpan.ParseExact(intervalString, format, culture);
Console.WriteLine("'{0}' --> {1}", intervalString, interval);
}
catch (FormatException) {
Console.WriteLine("'{0}': Bad Format for '{1}'",
intervalString, format);
}
catch (OverflowException) {
Console.WriteLine("'{0}': Overflow", intervalString);
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Date, Time, TimeZone