顾乔芝士网

持续更新的前后端开发技术栈

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

使用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()方法计算当前时间的前后日期。

喜欢的请关注和收藏!

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言