我有Date的字符串,它可以是任何格式的日期,但我想將它轉換爲dd-MM-yyyy
格式。
我已嘗試每個Convert.ToDatetime
選項,它只轉換爲系統格式。我希望它可以轉換成dd-MM-yyyy
格式。
Convert.ToDateTime('Datestring')爲需要的日期格式爲dd-MM-yyyy格式
請回復。提前致謝。
我有Date的字符串,它可以是任何格式的日期,但我想將它轉換爲dd-MM-yyyy
格式。
我已嘗試每個Convert.ToDatetime
選項,它只轉換爲系統格式。我希望它可以轉換成dd-MM-yyyy
格式。
Convert.ToDateTime('Datestring')爲需要的日期格式爲dd-MM-yyyy格式
請回復。提前致謝。
試試這個
DateTime dateTime = new DateTime();
dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDateString", "dd-MM-yyyy", CultureInfo.InvariantCulture));
這將返回DateTime
與Format
@RaviKPalanisamy如果這能解決您的問題,請接受答案! –
'Convert.ToDateTime'在這裏不需要,因爲'DateTime.ParseExact'已經返回一個DateTime對象。 – Boneless
DateTime.ParseExact
有一個重載的方法來接受多種格式,包括(所有)您可能收到的格式並解析字符串。一旦獲得有效的DateTime
,您可以在轉換爲字符串時應用所需的格式。
// ex...
string dateString = ...; // your date.
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
"MM/d/yyyy HH:mm:ss.ffffff" };
var date = DateTime.ParseExact(dateString, formats, new CultureInfo("en-US"), DateTimeStyles.None);
//convert to desired format.
var strDate = date.ToString("dd-MM-yyyy");
儘管有這許多人的答案,這是一個重複的答案,這裏有一些可能的解決方案:
string formatted = date.ToString("dd-MM-yyyy");
或
string formatted = date.ToString("dd MM yyyy");
This link可以幫助您更多格式和選項。
這裏,我們去:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "/" + time.Month + "/" + time.Year);
//返回:22/05/2016
試試這個一個
textBox1.Text = Convert.ToDateTime(read["Column-Name"]).ToString("dd-MM-yyy");
這不會**以有用的方式回答問題。爲什麼你認爲這是答案? _它是如何工作的?僅僅告訴某人在沒有任何語境或意義的情況下改變他們的代碼並不能幫助他們瞭解他們做錯了什麼。 – GrumpyCrouton
請分享迄今爲止所做的工作。此外,請檢查此http://stackoverflow.com/questions/15876418/datetime-today-tostringdd-mm-yyyy-returns-invalid-datetime-value – xCodeZone
你能分享你當前的日期字符串的輸出嗎? – SilentCoder
您必須爲此創建一個用戶定義的函數,它將拆分日期字符串並返回新的生成日期。 – Vipul