简体   繁体   中英

system date and time format change in C# windows application form using datetime.parseexact() function

I was trying this form but still got same format as a system format but instead of that I want to change date and time format. I am using combobox to change to the different formats.

Here is my code:

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 sytem_date_and_time_format_2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("dd-MM-yyyy");
            comboBox1.Items.Add("dd-MMM-yyyy");
            comboBox1.Items.Add("dd-MM-yy");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            DateTime datetime = DateTime.Now;
            this.label1.Text = datetime.ToString();

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == "dd-MM-yyyy")
            {
                string s = "22-02-2021";
                var date = DateTime.ParseExact(s, "dd-MM-yyyy", null);
                label2.Text = date.ToString();
            }
            else if (comboBox1.SelectedItem == "dd-MMM-yyyy")
            {
                string s = "22-Feb-2021";
                var date = DateTime.ParseExact(s, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
              
                label2.Text = date.ToString();
            }
        }
    }
}

You are parsing from a specific Date format into your DateTime object. But within this object the data is stored without any formatting details, so you need to provide formatting data when you output the object.

If you just do date.ToString() then it will use the system format (which is what you see now).

So instead you need to pass it details of what format to output such as;

date.ToString("dd-MM-yyyy");
date.ToString("dd-MMM-yyyy");
date.ToString("dd-MM-yy");

or if you want the selected value from the Combobox

date.ToString(comboBox1.SelectedItem.ToString());  //Note you need to check for null / no selected value / incorrect value otherwise this will throw an exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM