Convert String to Date - C #

How can I convert a string like "Monday, March 25, 2010 ..." to 25/03/10? Also, is this possible?

+5
source share
4 answers

You can use it DateTime.ParseExact, but I think you need to remove "On" before trying to analyze it.

EDIT According to the format documentation, you probably won’t need to disable On. after.

var theDate = DateTime.ParseExact(theString, "On dddd ddth MMMM yyy",
                  CultureInfo.InvariantCulture);

Must do it.

+15
source

. , 25-, 22- 23-. , .

string s = "On Monday 25th March 2010";
string pattern = @"^[^0-9]+(\d+)(\w\w)?";
string clean = Regex.Replace(s, pattern,@"$1");
string result = DateTime.ParseExact(clean,"dd MMMM yyyy",
      CultureInfo.InvariantCulture)
     .ToString("dd/MM/yy");
+2

, DateTime.ParseExact - . , ():

@"On dddd dd\t\h MMMM yyyy..."

't' 'h' , ( "AM/PM" "" ).

, . , 25 2010 , ; :

"On Thursday 25th March 2010..."

, :

"dd/MM/yy"
+1

:

using System; using System.Collections.Generic; using
System.ComponentModel; using System.Data; using System.Drawing; using
System.Text; using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
          label1.Text= ConvDate_as_str(textBox1.Text);
        }

        public string ConvDate_as_str(string dateFormat)
        {
            try
            {
                char[] ch = dateFormat.ToCharArray();
                string[] sps = dateFormat.Split(' ');
                string[] spd = sps[0].Split('.');
                dateFormat = spd[0] + ":" + spd[1]+" "+sps[1];
                DateTime dt = new DateTime();
                dt = Convert.ToDateTime(dateFormat);
                return dt.Hour.ToString("00") + dt.Minute.ToString("00");
            }
            catch (Exception ex)
            {
                return "Enter Correct Format like <5.12 pm>";
            }

        }


        private void button2_Click(object sender, EventArgs e)
        {
           label2.Text = ConvDate_as_date(textBox2.Text);
        }

        public string ConvDate_as_date(string stringFormat)
        {
            try
            {
                string hour = stringFormat.Substring(0, 2);
                string min = stringFormat.Substring(2, 2);
                DateTime dt = new DateTime();
                dt = Convert.ToDateTime(hour+":"+min);
                return String.Format("{0:t}", dt); ;
            }
            catch (Exception ex)
            {
                return "Please Enter Correct format like <0559>";
            }
        }
    }
}
-1

All Articles