.NET HELP C# Timespan Format (How it Works for Developers) Jacob Mellor 更新:2025年6月22日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在當今快節奏的開發世界中,處理時間間隔對於眾多應用程式至關重要,從專案管理系統到時間追蹤工具。 C# 中的TimeSpan結構提供了一種強大的方法來表示時間間隔,使開發人員能夠更輕鬆地執行計算並有效率地格式化時間資料。 結合IronPDF (一個功能強大的 .NET PDF 生成庫),可以根據時間數據建立動態、視覺效果吸引人的報告。 本文將深入探討 C# 中 TimeSpan 的格式化細節,並闡述如何將其與 IronPDF 無縫集成,以產生富有洞察力的報告。 無論您是追蹤員工工時還是衡量專案工期,本指南都將提供實用範例來增強您的報告能力。 理解 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 $vbLabelText $csharpLabel 這將顯示以下輸出: C# 時間跨度格式(開發者如何理解):圖 1 格式化顯示時間跨度 在顯示 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 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 '")); $vbLabelText $csharpLabel 此範例顯示以下輸出: C# 時間跨度格式(開發者如何理解):圖 2 使用 TimeSpan 和 IronPDF 產生 PDF 在 .NET 專案中設定 IronPDF 要開始使用IronPDF ,您首先需要安裝它。 如果已經安裝了 IronPDF 庫,則可以跳到下一節;否則,以下步驟將介紹如何安裝 IronPDF 庫。 透過 NuGet 套件管理器控制台 若要使用 NuGet 套件管理器主控台安裝 IronPDF ,請開啟 Visual Studio 並導覽至套件管理器主控台。 然後運行以下命令: Install-Package IronPdf 透過 NuGet 套件管理器取得解決方案 開啟 Visual Studio,前往"工具 -> NuGet 套件管理員 -> 管理解決方案的 NuGet 套件",然後搜尋 IronPDF。 接下來,您只需選擇您的專案並點擊"安裝",IronPDF 就會新增到您的專案中。 C# 時間跨度格式(開發者如何理解):圖 3 安裝 IronPDF 後,您只需在程式碼頂部新增正確的 using 語句即可開始使用 IronPDF: using IronPdf; using IronPdf; $vbLabelText $csharpLabel 現在您已準備好使用 IronPDF 和 TimeSpan 來執行 PDF 生成任務。 使用 IronPDF 產生基於時間的報告 IronPDF 設定完成後,您可以使用 TimeSpan 數據產生資訊豐富的 PDF 報告。 例如,假設你需要為員工產生工作日誌。 您可以利用 TimeSpan 值有效地顯示任務持續時間和休息時間。 範例場景:在 PDF 報表中設定時間跨度值的格式 以下是如何在 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"); } $vbLabelText $csharpLabel C# 時間跨度格式(開發者如何理解):圖 4 在這個範例中,我們建立了一個簡單的表格來顯示員工的工作日誌。 GenerateWorkLogReport方法會產生一個包含格式化 TimeSpan 值的 HTML 表格,然後將其轉換為 PDF 文件。 我們使用 IronPDF 的ChromePdfRenderer類別來處理 HTML 內容到 PDF 格式的渲染。 PdfDocument用於建立 PDF 對象,該對像用於處理新建立的 PDF 並保存它。 報表中時間跨度格式設定和使用的進階技巧 針對不同使用場景自訂時間跨度輸出 自訂 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"); } } $vbLabelText $csharpLabel C# 時間跨度格式(開發者如何理解):圖 5 在這個例子中, ToString(@"hh\:mm")使用自訂格式字串將 TimeSpan 格式化為 09:30(總小時數和分鐘數)。 透過這種方式,您可以確保以您想要的方式顯示時間跨度,同時保持文件的可讀性。 也可以反過來,透過將字串解析為 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)</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); } } } $vbLabelText $csharpLabel C# 時間跨度格式(開發者如何理解):圖 6 在這個例子中,自訂方法FormatLargeTimeSpan將較大的 TimeSpan 值轉換為易於閱讀的格式,例如"6 天 5 小時 30 分鐘"。它會檢查 TimeSpan 值是否包含天,並根據情況使用支援複合格式的方法格式化輸出。 如果總時長超過 24 小時,則提取日期並與剩餘的小時和分鐘一起顯示。 對於少於一天的時間間隔,只顯示小時和分鐘。 為什麼選擇 IronPDF 來產生基於時間跨度的 PDF 檔案? IronPDF 在報表應用上的主要優勢 IronPDF 的突出特點在於其強大的功能,能夠根據字串、時間和 HTML 資料產生動態 PDF。 使用 IronPDF,處理 PDF 相關任務將變得輕而易舉。 從基本的 PDF 產生到安全的 PDF 加密,IronPDF 都能滿足您的需求。 主要優勢包括: HTML 轉 PDF:輕鬆將HTML 內容轉換為 PDF,同時保持佈局和設計。 IronPDF 還可以處理將許多其他文件類型轉換為 PDF,包括DOCX 、圖像、 URL和ASPX 。 *自訂選項:*使用自訂範本和格式自訂報告以滿足特定的業務需求,為您的 PDF 文件添加專業外觀的頁首和頁尾、目錄,甚至自訂背景。 像素級完美 PDF:** IronPDF 對現代網絡標準的強大支持,能夠生成與您的品牌視覺一致的高質量 PDF 文檔,即使是從網絡內容生成的 PDF 也能始終保持像素級完美。 與 .NET 和 TimeSpan 格式的無縫集成 IronPDF 與 .NET 應用程式無縫集成,使開發人員能夠有效地利用 TimeSpan 結構。 使用 IronPDF,您可以輕鬆產生包含格式化時間資料的專業報告,讓您的報告流程有效率且簡單。 結論 在本文中,我們探討如何在 C# 中格式化和處理TimeSpan值,並將其無縫整合到IronPDF中以產生基於時間的動態報告。 C# TimeSpan 格式結構是表示時間間隔(例如專案持續時間、工作日誌和任務完成時間)的重要工具。 無論處理的是短時間跨度還是跨越數天、數小時和數分鐘的大時間間隔,C# 都提供了靈活的格式化選項,以人類可讀的格式呈現這些數據。 更進階的範例可能包括遵循文化格式約定、取得時間輸入、將字串解析為 TimeSpan 等等。 IronPDF 能夠精確地將 HTML 轉換為 PDF,是產生資料驅動型應用程式報告的理想工具。 它與 C# 的整合使得將 TimeSpan 等複雜結構融入高品質 PDF 變得容易。 現在您已經了解如何使用 IronPDF 格式化 TimeSpan 值並將其整合到 PDF 報告中,是時候進行下一步了。下載 IronPDF免費試用版,探索其在為您的專案產生動態、數據驅動型報告方面的全部潛力。 使用 IronPDF,您可以輕鬆將基於時間的資料轉換為精美專業的文件。 常見問題解答 如何在 C# 中將 HTML 轉換為 PDF? 您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換成 PDF。您也可以使用 RenderHtmlFileAsPdf 將 HTML 檔案轉換成 PDF。 C# 中的 TimeSpan 結構有何用途? C# 中的 TimeSpan 結構用於表示時間間隔。它簡化了測量工期、計算時差等工作,並可與 IronPDF 等 PDF 產生函式庫整合,以建立詳細的時間型報表。 如何格式化 TimeSpan 物件以納入 PDF 報表? 若要格式化 TimeSpan 物件以納入 PDF 報表,您可以使用各種格式字串,例如「C」、「G」或自訂格式。格式化之後,就可以使用 IronPDF 將時間資料渲染成 PDF。 在產生 PDF 報告時,我可以自訂 TimeSpan 的輸出內容嗎? 是的,您可以使用格式字串自訂 TimeSpan 的輸出,以滿足特定的報表需求,例如只顯示小時和分鐘。IronPDF 允許將這些自訂格式的字串無縫整合到 PDF 報表中。 如何在 C# 中整合 PDF 生成庫與 TimeSpan? 若要在 C# 中將 IronPDF 之類的 PDF 產生函式庫與 TimeSpan 整合,您首先要根據需要格式化 TimeSpan 資料,然後再使用 IronPDF 將這些資料與其他內容轉換成 PDF 文件。 在 .NET 專案中安裝 PDF 產生函式庫的步驟為何? 若要在 .NET 專案中安裝 PDF 產生函式庫,您可以使用 Visual Studio 中的 NuGet Package Manager Console 執行適當的安裝指令,或利用 NuGet Package Manager for Solution 來新增函式庫。 如何處理較大的 TimeSpan 值,以提高 PDF 報表的可讀性? 對於較大的 TimeSpan 值,您可以將其轉換為人性化的字串,例如「3 天 5 小時」,以提高可讀性。IronPDF 允許您在 PDF 報表中包含這些格式化的字串,以獲得更好的呈現效果。 使用 PDF 產生函式庫建立報表有哪些優點? IronPDF 之類的 PDF 產生函式庫具有許多優點,例如可以將 HTML 轉換為 PDF、套用自訂範本,以及產生保持視覺一致性的高品質專業外觀報告。 Jacob Mellor 立即與工程團隊聊天 首席技術長 Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多 C# Async Await (How it Works for Developers)Parseint C# (How it Works for Devel...
更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多