C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# 时间和日期

C# 时间和日期的处理方法

作者:ghost143

这篇文章主要介绍了C#时间和日期的处理,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

时间和日期的核心概念

1. UTC 和 本地时间

UTC(Coordinated Universal Time):

本地时间(Local Time): 

2. UTC 和本地时间的区别

常用日期和时间类

1. DateTime

using System;
class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        DateTime utcNow = DateTime.UtcNow;
        DateTime today = DateTime.Today;
        Console.WriteLine($"Local Now: {now}");    //Local Now: 2025/6/4 14:05:43
        Console.WriteLine($"UTC Now: {utcNow}");   //UTC Now: 2025/6/4 6:05:43
        Console.WriteLine($"Today: {today}");      //Today: 2025/6/4 0:00:00
    }
}

2. TimeSpan 定义:

using System;
class Program
{
    static void Main()
    {
        TimeSpan duration = new TimeSpan(1, 2, 30); // 1 hour, 2 minutes, 30 seconds
        Console.WriteLine($"Duration: {duration}");  //Duration: 01:02:30
        TimeSpan fromHours = TimeSpan.FromHours(5.5);
        Console.WriteLine($"5.5 Hours in Total Minutes: {fromHours.TotalMinutes}");
        //5.5 Hours in Total Minutes: 330
    }
}

3.DateTimeOffset 

using System;
class Program
{
    static void Main()
    {
        // 获取当前时间的 Unix 时间戳(秒)
        long unixTimestampInSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        Console.WriteLine($"Unix 时间戳(秒):{unixTimestampInSeconds}");
        // 获取当前时间的 Unix 时间戳(毫秒)
        long unixTimestampInMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        Console.WriteLine($"Unix 时间戳(毫秒):{unixTimestampInMilliseconds}");
    }
}

日期和时间的格式化

使用DateTime.ToString方法和格式字符串自定义日期和时间的输出。

常见格式字符串:

using System;
class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        string formattedDate = now.ToString("yyyy-MM-dd");
        string formattedTime = now.ToString("HH:mm:ss");
        string fullDate = now.ToString("dddd, dd MMMM yyyy");
        Console.WriteLine($"Formatted Date: {formattedDate}"); //Formatted Date: 2025-06-04
        Console.WriteLine($"Formatted Time: {formattedTime}"); //Formatted Time: 14:12:14
        Console.WriteLine($"Full Date: {fullDate}"); //Full Date: 星期三, 04 六月 2025
    }
}

使用场景

通过理解这些日期和时间处理的概念和类,您可以有效地管理时间相关的数据和逻辑。如果有任何问题或者需要进一步指导,请随时告诉我! 

到此这篇关于C# 时间和日期的处理的文章就介绍到这了,更多相关C# 时间和日期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文