C# 時間間隔格式 (如何為開發人員運作)
在現今快節奏的開發世界中,從專案管理系統到時間追蹤工具,處理時間間隔對許多應用程式都至關重要。 C# 中的 TimeSpan 結構提供了一種強大的方式來表示時間間隔,讓開發人員更容易有效率地執行計算和格式化時間資料。 結合 IronPDF 這個功能強大的 .NET PDF 產生函式庫,可根據時間資料建立動態、具視覺吸引力的報表。
本文將深入探討在 C# 中格式化 TimeSpan 的複雜性,說明如何將其與 IronPDF 無縫整合,以產生有深度的報表。 無論您是追蹤員工工時或測量專案時間,本指南都會提供實用範例,以增強您的報告能力。
Understanding TimeSpan in C#
什麼是 C# 中的 TimeSpan?
C# 中的 TimeSpan 結構代表時間間隔,可用於測量持續時間或兩個日期與時間值之間的差異。 這是一種多功能的結構,可讓開發人員執行各種與時間相關的計算,例如:
- 計算任務的持續時間。
- 測量事件之間的時間差。
- 為效能測量建立計時器。
TimeSpan 的意義在於它能夠簡化並標準化各應用程式的時間間隔管理,讓處理各種時間相關工作變得更容易。
建立和使用 TimeSpan 的基本方法
建立 TimeSpan 物件非常簡單直接,有幾種方法可供使用,例如:
- TimeSpan.FromHours(double hours):建立一個表示指定小時數的 TimeSpan。
- TimeSpan.FromMinutes(double minutes):建立一個表示指定分鐘數的 TimeSpan。
- TimeSpan.FromSeconds(double seconds):建立一個表示指定秒數的 TimeSpan。
以下是一個範例,說明如何建立 TimeSpan 實例並在計算中使用它們:
// Creating TimeSpan instances
TimeSpan taskDuration = TimeSpan.FromHours(2.5); // 2 hours and 30 minutes
TimeSpan breakDuration = TimeSpan.FromMinutes(15); // 15 minutes
// Calculating total time spent
TimeSpan totalTime = taskDuration + breakDuration;
Console.WriteLine($"Total time spent: {totalTime}"); // Outputs: 02:45:00
// Creating TimeSpan instances
TimeSpan taskDuration = TimeSpan.FromHours(2.5); // 2 hours and 30 minutes
TimeSpan breakDuration = TimeSpan.FromMinutes(15); // 15 minutes
// Calculating total time spent
TimeSpan totalTime = taskDuration + breakDuration;
Console.WriteLine($"Total time spent: {totalTime}"); // Outputs: 02:45:00
' Creating TimeSpan instances
Dim taskDuration As TimeSpan = TimeSpan.FromHours(2.5) ' 2 hours and 30 minutes
Dim breakDuration As TimeSpan = TimeSpan.FromMinutes(15) ' 15 minutes
' Calculating total time spent
Dim totalTime As TimeSpan = taskDuration.Add(breakDuration)
Console.WriteLine($"Total time spent: {totalTime}") ' Outputs: 02:45:00
這會顯示以下輸出:

設定 TimeSpan 的顯示格式
在顯示 TimeSpan 值時,C# 提供了多種格式化選項。 Specifier 輸出用於控制 TimeSpan 值轉換為字串時的顯示方式。 這些規格定義了 TimeSpan 物件的輸出格式,有助於自訂其在最後 PDF 報告中的表示方式。 最常用的格式規範包括
- "c":不變格式(例如,1.02:30:45 表示 1 天 2 小時 30 分鐘 45 秒)。
- "g":標準格式說明符,如果日期部分為零,則排除日期部分(例如,02:30:45)。 *自訂格式:您可以定義自訂格式以滿足特定需求,例如僅顯示小時和分鐘或日期和小時。
以下是在報告或日誌中輸出 TimeSpan 格式化的範例:
TimeSpan duration = new TimeSpan(1, 2, 30, 45); // 1 day, 2 hours, 30 minutes, 45 seconds
// Default "c" format string produces the output: 1.02:30:45
Console.WriteLine(duration.ToString("c"));
// Custom format "hh:mm:ss" outputs: 26:30:45
Console.WriteLine(duration.ToString(@"hh\:mm\:ss"));
// Custom format with days, outputs: 1d 02h 30m
Console.WriteLine(duration.ToString(@"d'd 'hh'h 'mm'm '"));
TimeSpan duration = new TimeSpan(1, 2, 30, 45); // 1 day, 2 hours, 30 minutes, 45 seconds
// Default "c" format string produces the output: 1.02:30:45
Console.WriteLine(duration.ToString("c"));
// Custom format "hh:mm:ss" outputs: 26:30:45
Console.WriteLine(duration.ToString(@"hh\:mm\:ss"));
// Custom format with days, outputs: 1d 02h 30m
Console.WriteLine(duration.ToString(@"d'd 'hh'h 'mm'm '"));
Dim duration As New TimeSpan(1, 2, 30, 45) ' 1 day, 2 hours, 30 minutes, 45 seconds
' Default "c" format string produces the output: 1.02:30:45
Console.WriteLine(duration.ToString("c"))
' Custom format "hh:mm:ss" outputs: 26:30:45
Console.WriteLine(duration.ToString("hh\:mm\:ss"))
' Custom format with days, outputs: 1d 02h 30m
Console.WriteLine(duration.ToString("d'd 'hh'h 'mm'm '"))
本範例顯示以下輸出:

使用 TimeSpan 與 IronPDF 來產生 PDF 。
在您的 .NET 專案中設定 IronPDF
若要開始使用 IronPDF,您首先需要安裝它。 如果已安裝,則可跳至下一節,否則,以下步驟將介紹如何安裝 IronPDF 函式庫。
透過 NuGet 套件管理員控制台
要使用 NuGet Package Manager Console 安裝 IronPDF,請開啟 Visual Studio 並導航至 Package Manager Console。 然後執行以下指令:
Install-Package IronPdf
透過解決方案的 NuGet 套件管理員
打開 Visual Studio,進入"工具 -> NuGet 套件管理員 -> 管理解決方案的 NuGet 套件",搜尋 IronPDF。 在此,您只需選擇專案,然後點擊"安裝",IronPDF 即會加入您的專案中。

安裝 IronPDF 之後,您只需在程式碼頂端加上正確的 using statement 即可開始使用 IronPDF:
using IronPdf;
using IronPdf;
Imports IronPdf
現在您已準備好開始使用 IronPDF 和 TimeSpan 進行 PDF 生成任務了。
使用 IronPDF 產生以時間為基礎的報告
IronPDF 設定完成後,您就可以使用 TimeSpan 資料產生內容豐富的 PDF 報告。 例如,您需要為員工生成工作記錄。 您可以利用 TimeSpan 值來有效顯示任務時間和休息時間。
範例情境:在 PDF 報告中格式化 TimeSpan 值
以下是如何在 PDF 報表中使用 TimeSpan 資料,包括產生簡單的工作記錄:
using IronPdf;
public static void Main(string[] args)
{
TimeSpan duration = new TimeSpan(9, 30, 25);
var employees = new List<(string name, TimeSpan timeSpan)> {
("Jane Doe", duration),
("John Doe", duration)
};
GenerateWorkLogReport(employees);
}
public static void GenerateWorkLogReport(List<(string Employee, TimeSpan Duration)> workLogs)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
var htmlContent = "<h1>Work Log Report</h1><table border='1'><tr><th>Employee</th><th>Duration</th></tr>";
foreach (var log in workLogs)
{
htmlContent += $"<tr><td>{log.Employee}</td><td>{log.Duration.ToString(@"hh\:mm\:ss")}</td></tr>";
}
htmlContent += "</table>";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("WorkLogReport.pdf");
}
using IronPdf;
public static void Main(string[] args)
{
TimeSpan duration = new TimeSpan(9, 30, 25);
var employees = new List<(string name, TimeSpan timeSpan)> {
("Jane Doe", duration),
("John Doe", duration)
};
GenerateWorkLogReport(employees);
}
public static void GenerateWorkLogReport(List<(string Employee, TimeSpan Duration)> workLogs)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
var htmlContent = "<h1>Work Log Report</h1><table border='1'><tr><th>Employee</th><th>Duration</th></tr>";
foreach (var log in workLogs)
{
htmlContent += $"<tr><td>{log.Employee}</td><td>{log.Duration.ToString(@"hh\:mm\:ss")}</td></tr>";
}
htmlContent += "</table>";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("WorkLogReport.pdf");
}
Imports IronPdf
Public Shared Sub Main(ByVal args() As String)
Dim duration As New TimeSpan(9, 30, 25)
Dim employees = New List(Of (name As String, timeSpan As TimeSpan)) From {("Jane Doe", duration), ("John Doe", duration)}
GenerateWorkLogReport(employees)
End Sub
Public Shared Sub GenerateWorkLogReport(ByVal workLogs As List(Of (Employee As String, Duration As TimeSpan)))
Dim renderer As New ChromePdfRenderer()
Dim htmlContent = "<h1>Work Log Report</h1><table border='1'><tr><th>Employee</th><th>Duration</th></tr>"
For Each log In workLogs
htmlContent &= $"<tr><td>{log.Employee}</td><td>{log.Duration.ToString("hh\:mm\:ss")}</td></tr>"
Next log
htmlContent &= "</table>"
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("WorkLogReport.pdf")
End Sub

在這個範例中,我們建立了一個簡單的表格來顯示員工的工作記錄。 GenerateWorkLogReport 方法會產生具有格式化 TimeSpan 值的 HTML 表格,然後將其轉換為 PDF 文件。 我們使用 IronPDF 的 ChromePdfRenderer 類來處理將 HTML 內容渲染為 PDF 格式。 PdfDocument用於建立 PDF 物件,用於處理新建立的 PDF 並將其儲存。
在報表中格式化和使用 TimeSpan 的進階技術
針對不同的使用個案自訂 TimeSpan 輸出
自訂 TimeSpan 輸出可大幅提升報告的可讀性。 舉例來說,如果您只需要顯示小時和分鐘,您可以依此來格式化 TimeSpan。 在這個範例中,我們將採用上一個範例中建立的相同員工資料,並將 TimeSpan 格式化為只顯示他們工作的小時和分鐘。 在此情況下,秒數對於記錄而言並非必要,而且只會佔用不必要的空間,因此我們會將其格式化:
using IronPdf;
class Program
{
public static void Main(string[] args)
{
TimeSpan duration = new TimeSpan(9, 30, 25);
var employees = new List<(string name, TimeSpan timeSpan)> {
("Jane Doe", duration),
("John Doe", duration)
};
GenerateWorkLogReport(employees);
}
public static void GenerateWorkLogReport(List<(string Employee, TimeSpan Duration)> workLogs)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
var htmlContent = "<h1>Work Log Report</h1><table border='1'><tr><th>Employee</th><th>Duration</th></tr>";
foreach (var log in workLogs)
{
// Custom format string to format the TimeSpan value for display
string formattedDuration = log.Duration.ToString(@"hh\:mm");
htmlContent += $"<tr><td>{log.Employee}</td><td>{formattedDuration}</td></tr>";
}
htmlContent += "</table>";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("WorkLogReport.pdf");
}
}
using IronPdf;
class Program
{
public static void Main(string[] args)
{
TimeSpan duration = new TimeSpan(9, 30, 25);
var employees = new List<(string name, TimeSpan timeSpan)> {
("Jane Doe", duration),
("John Doe", duration)
};
GenerateWorkLogReport(employees);
}
public static void GenerateWorkLogReport(List<(string Employee, TimeSpan Duration)> workLogs)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
var htmlContent = "<h1>Work Log Report</h1><table border='1'><tr><th>Employee</th><th>Duration</th></tr>";
foreach (var log in workLogs)
{
// Custom format string to format the TimeSpan value for display
string formattedDuration = log.Duration.ToString(@"hh\:mm");
htmlContent += $"<tr><td>{log.Employee}</td><td>{formattedDuration}</td></tr>";
}
htmlContent += "</table>";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("WorkLogReport.pdf");
}
}
Imports IronPdf
Friend Class Program
Public Shared Sub Main(ByVal args() As String)
Dim duration As New TimeSpan(9, 30, 25)
Dim employees = New List(Of (name As String, timeSpan As TimeSpan)) From {("Jane Doe", duration), ("John Doe", duration)}
GenerateWorkLogReport(employees)
End Sub
Public Shared Sub GenerateWorkLogReport(ByVal workLogs As List(Of (Employee As String, Duration As TimeSpan)))
Dim renderer As New ChromePdfRenderer()
Dim htmlContent = "<h1>Work Log Report</h1><table border='1'><tr><th>Employee</th><th>Duration</th></tr>"
For Each log In workLogs
' Custom format string to format the TimeSpan value for display
Dim formattedDuration As String = log.Duration.ToString("hh\:mm")
htmlContent &= $"<tr><td>{log.Employee}</td><td>{formattedDuration}</td></tr>"
Next log
htmlContent &= "</table>"
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("WorkLogReport.pdf")
End Sub
End Class

在這個範例中,ToString(@"hh\:mm") 使用自訂格式字串將 TimeSpan 格式化為 09:30(總時數和分數)。 使用此功能,您可以確保 TimeSpan 以您希望的方式顯示,以維持文件的可讀性。 這也可以反向進行,將字串解析為 TimeSpan。 解析會將遵循特定格式 (如"hh:mm"或"d.hh:mm") 的輸入字串轉換為實際的 TimeSpan 物件,讓 C# 可以程式化地使用該物件。
處理較大的時間間隔和可讀性格式
在處理較大的 TimeSpan 值時,為了可讀性,格式化是很重要的。 例如,您可以將較長的工期轉換成較易理解的格式,如"3 天 5 小時":
class Program
{
public static void Main(string[] args)
{
// Sample data: List of employee names and their work durations (TimeSpan)
var workLogs = new List<(string Employee, TimeSpan Duration)>
{
("Alice", new TimeSpan(5, 30, 0)), // 5 hours, 30 minutes
("Bob", new TimeSpan(3, 15, 0)), // 3 hours, 15 minutes
("Charlie", new TimeSpan(7, 45, 0)) // 7 hours, 45 minutes
};
// Create the HTML content for the PDF report
string htmlContent = @"
<h1>Work Log Report</h1>
<table border='1' cellpadding='5' cellspacing='0'>
<tr>
<th>Employee</th>
<th>Work Duration (hh:mm)</th>
</tr>";
// Loop through the work logs and add rows to the table
foreach (var log in workLogs)
{
string formattedDuration = FormatLargeTimeSpan(log.Duration); // Custom method to format large TimeSpan values
htmlContent += $"<tr><td>{log.Employee}</td><td>{formattedDuration}</td></tr>";
}
// Close the HTML table
htmlContent += "</table>";
// Create a new HtmlToPdf renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML content as a PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdf.SaveAs("WorkLogReport.pdf");
}
// Custom method to handle the formatting operation
static string FormatLargeTimeSpan(TimeSpan timeSpan)
{
// Check if there are days in the TimeSpan and format accordingly
if (timeSpan.TotalDays >= 1)
{
return string.Format("{0} days, {1} hours, {2} minutes",
(int)timeSpan.TotalDays,
timeSpan.Hours,
timeSpan.Minutes);
}
else
{
// If the duration is less than a day, show only hours and minutes
return string.Format("{0} hours, {1} minutes", timeSpan.Hours, timeSpan.Minutes);
}
}
}
class Program
{
public static void Main(string[] args)
{
// Sample data: List of employee names and their work durations (TimeSpan)
var workLogs = new List<(string Employee, TimeSpan Duration)>
{
("Alice", new TimeSpan(5, 30, 0)), // 5 hours, 30 minutes
("Bob", new TimeSpan(3, 15, 0)), // 3 hours, 15 minutes
("Charlie", new TimeSpan(7, 45, 0)) // 7 hours, 45 minutes
};
// Create the HTML content for the PDF report
string htmlContent = @"
<h1>Work Log Report</h1>
<table border='1' cellpadding='5' cellspacing='0'>
<tr>
<th>Employee</th>
<th>Work Duration (hh:mm)</th>
</tr>";
// Loop through the work logs and add rows to the table
foreach (var log in workLogs)
{
string formattedDuration = FormatLargeTimeSpan(log.Duration); // Custom method to format large TimeSpan values
htmlContent += $"<tr><td>{log.Employee}</td><td>{formattedDuration}</td></tr>";
}
// Close the HTML table
htmlContent += "</table>";
// Create a new HtmlToPdf renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML content as a PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdf.SaveAs("WorkLogReport.pdf");
}
// Custom method to handle the formatting operation
static string FormatLargeTimeSpan(TimeSpan timeSpan)
{
// Check if there are days in the TimeSpan and format accordingly
if (timeSpan.TotalDays >= 1)
{
return string.Format("{0} days, {1} hours, {2} minutes",
(int)timeSpan.TotalDays,
timeSpan.Hours,
timeSpan.Minutes);
}
else
{
// If the duration is less than a day, show only hours and minutes
return string.Format("{0} hours, {1} minutes", timeSpan.Hours, timeSpan.Minutes);
}
}
}
Imports System
Friend Class Program
Public Shared Sub Main(ByVal args() As String)
' Sample data: List of employee names and their work durations (TimeSpan)
Dim workLogs = New List(Of (Employee As String, Duration As TimeSpan)) From {("Alice", New TimeSpan(5, 30, 0)), ("Bob", New TimeSpan(3, 15, 0)), ("Charlie", New TimeSpan(7, 45, 0))}
' Create the HTML content for the PDF report
Dim htmlContent As String = "
<h1>Work Log Report</h1>
<table border='1' cellpadding='5' cellspacing='0'>
<tr>
<th>Employee</th>
<th>Work Duration (hh:mm)</th>
</tr>"
' Loop through the work logs and add rows to the table
For Each log In workLogs
Dim formattedDuration As String = FormatLargeTimeSpan(log.Duration) ' Custom method to format large TimeSpan values
htmlContent &= $"<tr><td>{log.Employee}</td><td>{formattedDuration}</td></tr>"
Next log
' Close the HTML table
htmlContent &= "</table>"
' Create a new HtmlToPdf renderer
Dim renderer As New ChromePdfRenderer()
' Render the HTML content as a PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF to a file
pdf.SaveAs("WorkLogReport.pdf")
End Sub
' Custom method to handle the formatting operation
Private Shared Function FormatLargeTimeSpan(ByVal timeSpan As TimeSpan) As String
' Check if there are days in the TimeSpan and format accordingly
If timeSpan.TotalDays >= 1 Then
Return String.Format("{0} days, {1} hours, {2} minutes", CInt(Math.Truncate(timeSpan.TotalDays)), timeSpan.Hours, timeSpan.Minutes)
Else
' If the duration is less than a day, show only hours and minutes
Return String.Format("{0} hours, {1} minutes", timeSpan.Hours, timeSpan.Minutes)
End If
End Function
End Class

在這個範例中,自訂方法 FormatLargeTimeSpan 會將大型 TimeSpan 值轉換成容易閱讀的格式,例如"6 天 5 小時 30 分鐘"。它會檢查 TimeSpan 值是否包含天數,並使用支援複合格式化的方法來對輸出進行相應的格式化。
- 如果總時間超過 24 小時,則會提取天數,並與剩餘的小時和分鐘一起顯示。
- 對於少於一天的時間間隔,只顯示小時和分鐘。
為何要選擇 IronPDF 進行基於時間跨度的 PDF 生成?
適用於報表應用程式的 IronPDF 的主要優點
IronPDF 在根據字串、時間和 HTML 資料生成動態 PDF 方面的強大功能脫穎而出。 有了 IronPDF,您的 PDF 相關任務將變得輕而易舉。 從基本的 PDF 產生到安全的 PDF 加密,IronPDF 都能滿足您的需求。 一些主要優點包括
與 .NET 和 TimeSpan 格式化的無縫整合
IronPDF 可與 .NET 應用程式無縫整合,讓開發人員有效利用 TimeSpan 結構。 使用 IronPDF,您可以以最小的工作量產生包含格式化時間資料的專業報告,使您的報告流程高效而直接。
結論
在本文中,我們探討了如何在 C# 中格式化並處理 TimeSpan 值,並將其無縫整合至 IronPDF 以產生以時間為基礎的動態報表。 C# TimeSpan 格式結構是表示時間間隔的必要工具,例如專案工期、工作記錄和任務完成時間。 無論您要處理的是短時間跨度或跨越數天、數小時和數分鐘的大間隔,C# 都能提供靈活的格式選項,以人類可讀的格式呈現這些資料。 接下來更進階的範例可能包括遵循文化的格式慣例、採用時間輸入、將字串解析為 TimeSpan 等。
IronPDF 擅於精準地將 HTML 轉換為 PDF,是從資料驅動應用程式產生報告的理想工具。 它與 C# 的整合讓您可以輕鬆地將複雜的結構(如 TimeSpan)融入高品質的 PDF 中。
現在您已瞭解如何格式化 TimeSpan 值,並使用 IronPDF 將其整合至 PDF 報表中,是時候進行下一步了。下載 免費試用版 IronPDF,探索它在為您的專案生成動態、資料驅動報表方面的全部潛力。 有了 IronPDF,您只需花最少的精力,就能將您的時間型資料轉換成精煉、專業的文件。
常見問題
怎樣在 C# 中將 HTML 轉換為 PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字符串轉換為 PDF。您還可以使用 RenderHtmlFileAsPdf 將 HTML 文件轉換為 PDF。
C# 中的 TimeSpan 結構用於什麼?
C# 中的 TimeSpan 結構用於表示時間間隔。它簡化了測量持續時間、計算時間差等任務,並可以與 IronPDF 等 PDF 生成庫集成來創建詳細的基於時間的報告。
如何格式化 TimeSpan 對象以包含在 PDF 報告中?
要格式化用於包含在 PDF 報告中的 TimeSpan 對象,可以使用多種格式字符串,如 "c"、"g" 或自定義格式。一旦格式化,時間資料可以使用 IronPDF 渲染成 PDF。
生成 PDF 報告時,我可以自定義 TimeSpan 的輸出嗎?
是的,您可以使用格式字符串自定義 TimeSpan 的輸出以滿足特定報告需求,例如僅顯示小時和分鐘。 IronPDF 允許這些自定義格式字符串無縫整合到 PDF 報告中。
如何將 PDF 生成庫與 C# 中的 TimeSpan 集成?
要將 PDF 生成庫(如 IronPDF)與 C# 中的 TimeSpan 集成,您首先要根據需要格式化 TimeSpan 資料,然後使用 IronPDF 將這些資料與其他內容一起轉換為 PDF 文檔。
在 .NET 項目中安裝 PDF 生成庫的步驟有哪些?
要在 .NET 項目中安裝 PDF 生成庫,您可以在 Visual Studio 的 NuGet 包管理器控制台中執行適當的安裝命令,或利用解決方案的 NuGet 包管理器來添加庫。
如何處理大型 TimeSpan 值以提高 PDF 報告的可讀性?
對於大型 TimeSpan 值,您可以通過將它們轉換為如「3 天 5 小時」這樣的人性化字符串來提高可讀性。 IronPDF 允許您在 PDF 報告中包含這些格式化的字符串,以提高展示效果。
使用 PDF 生成庫創建報告有哪些優勢?
像 IronPDF 的 PDF 生成庫提供了許多優勢,例如能將 HTML 轉換為 PDF、應用自定義模板,以及生成高質量、外觀專業的報告,保持視覺的一致性。



