C#编程显示特定的日期格式,并且计算当前日期的前后日期源代码

C#编程显示特定的日期格式,并且计算当前日期的前后日期源代码

编码文章call10242024-12-22 14:42:2517A+A-

使用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;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            inirq();
        }
        private string str_rq;
        private void inirq()
        {
            comboBox1.Items.Add("2001/1/1");
            comboBox1.Items.Add("2001年1月");
            comboBox1.Items.Add("2001年1月1日");
            comboBox1.Items.Add("2001年1月1日 00:00");
            comboBox1.Items.Add("2001年1月1日 00:00:00");
            comboBox1.Items.Add("自定义格式");
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(comboBox1.SelectedIndex==0)
            {
                str_rq = "d";
            }
            else if (comboBox1.SelectedIndex == 1)
            {
                str_rq = "y";
            }
            else if (comboBox1.SelectedIndex == 2)
            {
                str_rq = "D";
            }
            else if (comboBox1.SelectedIndex == 3)
            {
                str_rq = "f";
            }
            else if (comboBox1.SelectedIndex == 4)
            {
                str_rq = "F";
            }
            else if (comboBox1.SelectedIndex == 5)
            {
                str_rq = "yyyy年MM月dd日 HH时mm分ss秒";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = DateTime.Now.ToString(str_rq);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            texToday.Text = DateTime.Now.ToString("D");
            texYesterday.Text = DateTime.Now.AddDays(-1).ToString("D");
            texTomorrow.Text = DateTime.Now.AddDays(1).ToString("D");
        }
    }
}

结语:

学会使用Items.Add方法添加下拉列表框和利用SelectedIndex选中索引进行判断,会使用DateTime.Now.ToString()方法的指定日期格式,并且掌握AddDays()方法计算当前时间的前后日期。

喜欢的请关注和收藏!

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4