Convert string to Date - C#
How would I be able to convert a string like "On Monday 25th March 201开发者_如何学运维0..." to 25/03/10? Also, is this possible?
You can use DateTime.ParseExact
, but I think you have to strip "On " before trying to parse it.
EDIT According to the format documentation you probably do not have to strip "On " afterall.
var theDate = DateTime.ParseExact(theString, "On dddd ddth MMMM yyy",
CultureInfo.InvariantCulture);
Should do it.
You can't do this with date parsing alone. Any format string that works for the 25th is going to fail for the 22nd or 23rd. Personally, I'd use a regular expression to strip the date into something parsable.
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");
As klausbyskov points out,DateTime.ParseExact
is the way to go.
I believe the correct format string you need is (tested):
@"On dddd dd\t\h MMMM yyyy..."
The 't' and 'h ' characters need to be escaped since they carry special significance ('AM/PM' and 'hour' respectively).
Note though, that the parser will carry out some validation checks. In particular, your example will fail to parse since the 25th of March, 2010 happened to be a thursday; try it with:
"On Thursday 25th March 2010..."
As for the the output, the format string you need is:
"dd/MM/yy"
use this:
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>";
}
}
}
}
精彩评论