.NET 幫助

C# 時間跨度格式(開發人員如何使用)

發佈 2025年1月14日
分享:

介紹

在當今快速發展的世界中,處理時間間隔對於許多應用程式十分重要,從專案管理系統到時間追蹤工具皆是如此。 這TimeSpanC# 中的結構提供了一種強大的方式來表示時間間隔,使開發人員更容易進行計算和高效地格式化時間數據。 將此與IronPDF一個強大的 .NET PDF 生成庫,可基於時間數據創建動態、視覺上吸引人的報告。

本文將深入探討在 C# 中格式化 TimeSpan 的細節,說明如何將其與 IronPDF 無縫整合以生成有見地的報告。 無論您是在追蹤員工的工作時數還是測量專案的持續時間,本指南將提供實用的範例以增強您的報告能力。

理解 C#中的 TimeSpan

C# 中的 TimeSpan 是什麼?

C# 中的 TimeSpan 結構表示一個時間間隔,可用於測量持續時間或兩個日期和時間值之間的差異。 這是一個多功能的結構,使開發人員能夠執行各種時間相關的計算,例如:

  • 計算任務的持續時間。
  • 測量事件之間的時間差異。
  • 創建計時器進行性能測量。

    TimeSpan 的意義在於其能夠簡化和標準化跨應用程式的時間間隔管理,使處理各種與時間相關的任務更加容易。

創建和使用 TimeSpan 的基本方法

创建 TimeSpan 对象很简单,有多种方法可用,例如:

  • TimeSpan.FromHours(雙倍小時): 建立一個表示指定小時數的 TimeSpan。
  • TimeSpan.FromMinutes(雙精度分鐘数):建立表示指定分鐘數的 TimeSpan
  • TimeSpan.FromSeconds(雙精度秒):創建一個表示指定秒數的 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
VB   C#

這會顯示以下輸出:

C# Timespan 格式(開發人員如何運作):圖 1

格式化 TimeSpan 以供顯示

在顯示 TimeSpan 值時,C# 提供了多種格式化選項。 指定器輸出用於控制將 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 strings produce 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 strings produce 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 strings produce 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 '"))
VB   C#

此示例顯示以下輸出:

C# Timespan 格式(開發人員如何使用):圖2

使用TimeSpan與IronPDF進行PDF生成

在你的.NET專案中設置IronPDF

要開始使用IronPDF,您首先需要安裝它。 如果已經安裝,則可以跳到下一部分。否則,以下步驟將介紹如何安裝IronPDF庫。

透過 NuGet 套件管理器主控台

To安裝 IronPDF使用 NuGet 套件管理器主控台,開啟 Visual Studio 並導航至套件管理器主控台。 然後執行以下命令:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

透過 NuGet 封裝管理器為方案進行操作

打開 Visual Studio,前往「工具 -> NuGet 套件管理員 -> 為方案管理 NuGet 套件」並搜尋 IronPDF。 從這裡開始,您只需選擇您的專案並點擊「安裝」,IronPDF 就會被添加到您的專案中。

C# Timespan 格式(開發人員使用方式):圖 3

安裝 IronPDF 後,您只需在程式碼的頂部新增正確的 using 語句即可開始使用 IronPDF:

using IronPdf;
using IronPdf;
Imports IronPdf
VB   C#

現在,您已準備好開始使用 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
VB   C#

C# Timespan 格式(開發人員如何運作):圖 4

在此範例中,我們創建了一個簡單的表格來顯示員工工作日誌。 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
VB   C#

C# Timespan 格式(對開發人員的運作方式):圖 5

在此範例中,ToString(@"hh\:mm\:ss") 將 TimeSpan 格式化為 09:3(總小時和分鐘)使用自訂的格式字串時,應注意 TimeSpan 也支援標準格式字串類型的使用。使用這樣的方式,您可以確保 TimeSpan 的顯示符合您的需求,以維持文件的可讀性。 這也可以反過來進行,將字串解析為 TimeSpan。 解析將遵循特定格式的輸入字串進行轉換。(如 "hh:mm" 或 "d.hh:mm")轉換為 C# 可以以程式方式處理的實際 TimeSpan 物件。

處理大型時間間隔和格式化以提高可讀性

在處理較大的 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:ss)</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:ss)</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:ss)</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
VB   C#

C# 時間跨度格式(開發人員使用指南):圖 6

在此範例中,自訂方法 FormatLargeTimeSpan 將較大的 TimeSpan 值轉換成易於閱讀的格式,例如 "6 天,5 小時,30 分鐘"。它會檢查 TimeSpan 值是否包含天數,並使用支援複合格式的方法相應地格式化輸出。

  • 如果總持續時間超過24小時,則會提取天數並顯示剩餘的小時和分鐘。
  • 如果間隔少於一天,則只顯示小時和分鐘。

為什麼選擇 IronPDF 來進行基於 TimeSpan 的 PDF 生成?

IronPDF 對報告應用程式的主要優勢

IronPDF 因其在基於字符串、時間和 HTML 數據生成動態 PDF 的強大功能而脫穎而出。 使用IronPDF,您的PDF相關任務將變得輕而易舉。 從基本的 PDF 生成到安全的 PDF 加密,IronPDF 都能滿足您的需求。 一些主要好處包括:

  • HTML-to-PDF 轉換:輕鬆轉換HTML 內容將版面和設計轉換為PDF。 IronPDF 也能處理其他許多檔案類型轉換至 PDF,包括DOCX, 影像, 網址,和ASPX.
  • 自訂選項:使用自訂範本和格式調整報告以滿足特定的業務需求,使您的PDF文件看起來更專業。Header 和 Footer,目录、或甚至自訂背景.
  • 像素完美的 PDF:利用 IronPDF 對現代網頁標準的強大支持,生成與您的品牌形象在視覺上保持一致的高品質 PDF 文件,即使是從網頁內容生成的 PDF 也能始終達到像素完美的效果。

與 .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# Async Await(對開發人員的運作原理)
下一個 >
Parseint C#(對開發人員的工作原理)