Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#datetime

作者:刃起风啸凌   发布日期:2026-02-20   浏览:22

using System;

class Program
{
    static void Main()
    {
        // 获取当前日期和时间
        DateTime now = DateTime.Now;
        Console.WriteLine("当前日期和时间: " + now);

        // 创建一个特定日期和时间的 DateTime 对象
        DateTime specificDate = new DateTime(2023, 10, 5, 14, 30, 0);
        Console.WriteLine("特定日期和时间: " + specificDate);

        // 获取今天的日期
        DateTime today = DateTime.Today;
        Console.WriteLine("今天的日期: " + today);

        // 添加天数、小时等
        DateTime futureDate = now.AddDays(7); // 一周后
        Console.WriteLine("一周后的日期和时间: " + futureDate);

        // 格式化日期和时间
        string formattedDate = now.ToString("yyyy-MM-dd HH:mm:ss");
        Console.WriteLine("格式化后的日期和时间: " + formattedDate);

        // 比较两个 DateTime 对象
        if (now > specificDate)
        {
            Console.WriteLine("当前时间晚于特定时间");
        }
        else
        {
            Console.WriteLine("当前时间早于或等于特定时间");
        }
    }
}

解释说明:

  1. 获取当前日期和时间DateTime.Now 返回当前系统的日期和时间。
  2. 创建特定日期和时间:使用 new DateTime(year, month, day, hour, minute, second) 可以创建一个指定日期和时间的 DateTime 对象。
  3. 获取今天的日期DateTime.Today 返回今天的日期,但不包含时间部分(即时间为 00:00:00)。
  4. 添加天数、小时等:可以使用 AddDays()AddHours() 等方法来增加或减少日期和时间。
  5. 格式化日期和时间:使用 ToString("格式") 方法可以将 DateTime 对象格式化为字符串。
  6. 比较两个 DateTime 对象:可以直接使用比较运算符(如 >< 等)来比较两个 DateTime 对象。

上一篇:c# []

下一篇:c# oxyplot

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站