如何將字符串「2010年3月25日星期一...」轉換爲25/03/10? 另外,這可能嗎?將字符串轉換爲Date - C#
5
A
回答
15
你可以使用DateTime.ParseExact
,但我認爲你必須在試圖解析它之前去掉「On」。
編輯根據format documentation你可能不必去掉「On」。
var theDate = DateTime.ParseExact(theString, "On dddd ddth MMMM yyy",
CultureInfo.InvariantCulture);
應該這樣做。
1
正如klausbyskov指出,DateTime.ParseExact
是要走的路。 我相信你需要正確的格式字符串(測試):
@"On dddd dd\t\h MMMM yyyy..."
的「T」和需要進行轉義「H」字,因爲它們分別攜帶(「AM/PM」和「小時」的特殊意義)。
但請注意,解析器將執行一些驗證檢查。尤其是,自2010年3月25日恰好是星期四以來,你的榜樣將無法解析。與嘗試:
"On Thursday 25th March 2010..."
對於輸出,你需要的格式字符串:
"dd/MM/yy"
2
你不能單獨約會解析做到這一點。任何適用於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");
-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>";
}
}
}
}
+0
OP爲什麼要使用它?請解釋! – markus 2012-12-11 23:02:47
相關問題
- 1. 將字符串轉換爲'Date'類型
- 2. C++ - 將字符串轉換爲字符
- 3. Java字符串轉換爲Date
- 4. sql date轉換爲字符串格式
- 5. 我想從字符串轉換爲Date
- 6. 從字符轉換爲Date
- 7. C#將字符串轉換爲數字
- 8. 如何將「1987年1月」字符串轉換爲Date對象?
- 9. 將字符串轉換爲字符串
- 10. 將yyyymmdd字符串轉換爲R中的Date類
- 11. 如何將Objective-C字符串轉換爲C字符串?
- 12. 將字符串轉換爲位圖c#
- 13. C#將字符串轉換爲uint
- 14. C++將char轉換爲字符串
- 15. C#將Unicode轉換爲字符串
- 16. c#將字符串轉換爲變量
- 17. 將字符串轉換爲日期C++
- 18. 將字符串轉換爲System.guid c#
- 19. 將字符串轉換爲int在C++
- 20. 將字符串轉換爲smtpclient在c#
- 21. 將字符串轉換爲總和C#
- 22. C++ ::將ASCII值轉換爲字符串
- 23. 將C#貨幣轉換爲字符串
- 24. C:將int []轉換爲字符串
- 25. C#,將字符串轉換爲DateTimeOffset
- 26. 將字符串轉換爲long long C?
- 27. 將float轉換爲字符串c
- 28. C#:將字符串轉換爲DBType.AnsiStringFixedLength
- 29. 將double轉換爲字符串C++?
- 30. C:將int轉換爲字符串
你的意思是25/03/10? – 2010-10-22 16:44:34