优秀的编程知识分享平台

网站首页 > 技术文章 正文

C#编程有关时间的计算源代码(c#时间函数)

nanyue 2024-07-26 15:46:30 技术文章 4 ℃

C#编程有关时间的计算源代码:

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            long var_years = DateAndTime.DateDiff(DateInterval.Year, dateTimePicker1.Value, dateTimePicker2.Value);
            textBox1.Text = var_years.ToString() + "年";
            long var_months = DateAndTime.DateDiff(DateInterval.Month, dateTimePicker1.Value, dateTimePicker2.Value);
            textBox2.Text = var_months.ToString() + "个月";
            long var_days = DateAndTime.DateDiff(DateInterval.Day, dateTimePicker1.Value, dateTimePicker2.Value);
            textBox3.Text = var_days.ToString() + "天";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //增加时间段
            DateTime add_minute = DateAndTime.DateAdd(DateInterval.Minute,1, dateTimePicker3.Value);
            tex_AddM.Text = add_minute.ToString("F") ;
            DateTime add_hour = DateAndTime.DateAdd(DateInterval.Hour, 1, dateTimePicker3.Value);
            tex_AddH.Text = add_hour.ToString("F");
            DateTime add_day = DateAndTime.DateAdd(DateInterval.Day, 1, dateTimePicker3.Value);
            tex_AddD.Text = add_day.ToString("F");
            //减少时间段
            DateTime subtract_minute = DateAndTime.DateAdd(DateInterval.Minute, -1, dateTimePicker3.Value);
            tex_SubtractM.Text = subtract_minute.ToString("F");
            DateTime subtract_hour = DateAndTime.DateAdd(DateInterval.Hour, -1, dateTimePicker3.Value);
            tex_SubtractH.Text = subtract_hour.ToString("F");
            DateTime subtract_day = DateAndTime.DateAdd(DateInterval.Day, -1, dateTimePicker3.Value);
            tex_SubtractD.Text = subtract_day.ToString("F");
        }
    }
}

结语:

学会使用DateAndTime类中的DateDifff()方法和DateAdd()方法,并掌握输出指定格式的字符串。

喜欢的请关注和收藏!

最近发表
标签列表