.NET 帮助

C# 时间跨度格式(开发人员是如何工作的)

发布 2025年一月14日
分享:

介绍

在当今快速发展的世界中,处理时间间隔对于从项目管理系统到时间跟踪工具等众多应用来说至关重要。 "(《世界人权宣言》)TimeSpanC#中的结构体提供了一种强大的方式来表示时间间隔,使开发人员能够更轻松地执行计算并有效地格式化时间数据。 结合这一点与IronPDF,强大的 PDF 生成库用于 .NET,可基于时间数据创建动态、视觉吸引力的报告。

本文将深入探讨在C#中格式化TimeSpan的复杂性,说明如何将其无缝集成到IronPDF中以生成有见地的报告。 无论您是在跟踪员工工作时间还是在测量项目时长,本指南都将提供实用示例,以提高您的报告能力。

理解 C# 中的 TimeSpan

TimeSpan 在 C# 中是什么?

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# 时间间隔格式(开发人员如何使用):图 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# 时间跨度格式(开发者工作原理):图2

在使用IronPDF进行PDF生成时使用TimeSpan

在您的 .NET 项目中设置 IronPDF

开始使用IronPDF请注意,您首先需要安装它。 如果已经安装,则可以跳到下一节,否则,以下步骤将介绍如何安装 IronPDF 库。

通过 NuGet 软件包管理器控制台

安装 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# 时间跨度格式(开发人员是如何使用的):图 4

在这个例子中,我们创建了一个简单的表格来显示员工的工作日志。 GenerateWorkLogReport 方法生成一个包含格式化 TimeSpan 值的 HTML 表格,然后将其转换为 PDF 文档。 我们使用IronPDF的ChromePdfRenderer用于将 HTML 内容渲染为 PDF 格式的类。 PDF文档用于创建 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# Timespan 格式(开发人员如何使用):图 6

在此示例中,自定义方法FormatLargeTimeSpan将较大的TimeSpan值转换为易于阅读的格式,例如“6天,5小时,30分钟”。它会检查TimeSpan值是否包含天数,并根据需要格式化输出,使用支持复合格式的方法。

  • 如果总时长超过24小时,则会提取天数,并与剩余的小时和分钟一起显示。
  • 对于少于一天的时间间隔,仅显示小时和分钟。

为什么选择IronPDF进行基于TimeSpan的PDF生成?

IronPDF在报告应用程序中的关键优势

IronPDF 因其在基于字符串、时间和 HTML 数据生成动态 PDF 的强大功能而脱颖而出。 使用IronPDF,处理PDF相关任务将变得轻而易举。 从基本的PDF生成到安全的PDF加密,IronPDF都能满足您的需求。 一些主要好处包括:

  • HTML 到 PDF 转换:轻松转换HTML 内容PDF时保持布局和设计。 IronPDF 还可以将许多其他文件类型转换为 PDF,包括DOCX, 图像, 网址ASPX.
  • 定制选项:通过自定义模板和格式调整报告以满足特定的业务需求,使您的PDF文件看起来更专业。页眉和页脚一个目录,甚至自定义背景.
  • 像素完美的PDF:生成与您的品牌视觉一致的高质量PDF文档,得益于IronPDF对现代网络标准的强大支持,即使是从网络内容生成的PDF也将始终完美呈现。

与.NET和TimeSpan格式化无缝集成

IronPDF可以无缝集成到.NET应用程序中,允许开发人员有效利用TimeSpan结构。 使用IronPDF,您可以轻松生成包含格式化时间数据的专业报告,从而使您的报告过程高效且简单。

结论

在本文中,我们探讨了如何在 C# 中格式化和处理 TimeSpan 值,并将它们无缝集成到系统中。IronPDF生成动态的时间报告。 C# 的 TimeSpan 格式结构是表示时间间隔的重要工具,例如项目持续时间、工作日志和任务完成时间。 无论您是在处理短时间跨度还是跨越几天、几小时和几分钟的长时间间隔,C#都提供灵活的格式选项,以人类可读的格式呈现这些数据。 接下来,更高级的示例可能包括遵循文化格式规范、接收时间输入、将字符串解析为TimeSpan等。

IronPDF 在将 HTML 转换为 PDF 方面表现出色,是从数据驱动应用程序生成报告的理想工具。 与C#的集成使得将像TimeSpan这样的复杂结构轻松整合到高质量的PDF中。

现在您已经了解如何格式化TimeSpan值并将它们整合到PDF报告中使用IronPDF,是时候迈出下一步了。下载一个免费试用利用IronPDF,探索其在为您的项目生成动态数据驱动报告方面的全部潜力。 使用 IronPDF,您可以轻松地将基于时间的数据转化为精致的专业文档。

< 前一页
C# 异步等待(开发人员工作原理)
下一步 >
Parseint C#(开发人员工作原理)