# TimeSpan.FromSeconds 方法

2013/12/13

Namespace:  System

## 语法

```public static TimeSpan FromSeconds(
double value
)
```

value

## 例外

OverflowException

value 小于 MinValue 或大于 MaxValue

- 或 -

valueDouble.PositiveInfinity

- 或 -

valueDouble.NegativeInfinity

ArgumentException

value 等于 Double.NaN

## 备注

value 参数转换为毫秒，毫秒又转换为刻度，而该刻度数将用于初始化新的 TimeSpan。因此，只认为 value 精确到最近的毫秒。请注意，由于 Double 数据类型的精度丢失，对接近但仍处于 MinValueMaxValue 范围内的值，这会生成 OverflowException。例如在下列实例化 TimeSpan 对象的尝试中，这就是导致 OverflowException 的原因。

```
// The following throws an OverflowException at runtime
TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds);

```

## 示例

```
// Example of the TimeSpan.FromSeconds( double ) method.
using System;

class Example
{
static void GenTimeSpanFromSeconds(System.Windows.Controls.TextBlock outputBlock, double seconds)
{
// Create a TimeSpan object and TimeSpan string from
// a number of seconds.
TimeSpan interval = TimeSpan.FromSeconds(seconds);
string timeInterval = interval.ToString();

// Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
int pIndex = timeInterval.IndexOf(':');
pIndex = timeInterval.IndexOf('.', pIndex);
if (pIndex < 0) timeInterval += "        ";

outputBlock.Text += String.Format("{0,21}{1,26}", seconds, timeInterval) + "\n";
}

public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
outputBlock.Text +=
"This example of TimeSpan.FromSeconds( double )\n" +
"generates the following output.\n" + "\n";
outputBlock.Text += "{0,21}{1,18}",
"FromSeconds", "TimeSpan" + "\n";
outputBlock.Text += "{0,21}{1,18}",
"-----------", "--------" + "\n";

GenTimeSpanFromSeconds(outputBlock, 0.001);
GenTimeSpanFromSeconds(outputBlock, 0.0015);
GenTimeSpanFromSeconds(outputBlock, 12.3456);
GenTimeSpanFromSeconds(outputBlock, 123456.7898);
GenTimeSpanFromSeconds(outputBlock, 1234567898.7654);
GenTimeSpanFromSeconds(outputBlock, 1);
GenTimeSpanFromSeconds(outputBlock, 60);
GenTimeSpanFromSeconds(outputBlock, 3600);
GenTimeSpanFromSeconds(outputBlock, 86400);
GenTimeSpanFromSeconds(outputBlock, 1801220.2);
}
}

/*
This example of TimeSpan.FromSeconds( double )
generates the following output.

FromSeconds          TimeSpan
-----------          --------
0.001          00:00:00.0010000
0.0015          00:00:00.0020000
12.3456          00:00:12.3460000
123456.7898        1.10:17:36.7900000
1234567898.7654    14288.23:31:38.7650000
1          00:00:01
60          00:01:00
3600          01:00:00
86400        1.00:00:00
1801220.2       20.20:20:20.2000000
*/

```

Windows Phone