我的程序必須接受用戶以這種格式的月份,日期,年份(mm/dd/yyyy)輸入的日期,而不是以任何其他順序輸入,並且如果輸入的詳細信息以此格式輸入(mm/dd/yyyy)它被存儲在多維數組中。接收特定格式的數據
-1
A
回答
2
使用DateTime.ParseExact
用正確的格式字符串和CultureInfo.InvariantCulture
dates[0] = DateTime.ParseExact("07/28/2013", "MM/dd/yyyy", CultureInfo.InvariantCulture);
/
通常是您當前區域性的日期分隔符(例如-
或.
)的替代字符。要強制執行/
作爲分隔符,您需要指定CultureInfo.InvariantCulture
。
參見:The "/" Custom Format Specifier
您可以使用DateTime.TryParseExact
來檢查用戶輸入有效的格式:
DateTime dt;
if (DateTime.TryParseExact("07/28/2013", "MM/dd/yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None, out dt))
{
// valid date
}
0
假設用戶輸入的日期在TextBox
DateTime Test;
if (DateTime.TryParseExact(textBox1.Text, "mm/dd/yyyy", null, System.Globalization.DateTimeStyles.None, out Test) == true)
//do whatever
else
//do something else
+0
'null'作爲第三個參數意味着_current culture_。因此,根據實際的日期分隔符,這種格式將被轉換爲'「mm-dd-yyyy」或「mm.dd.yyyy」。 –
+0
感謝您強調這一點,蒂姆! –
0
我米不知道你的意思是
它已經存儲在多維數組中。
這裏是一個完整的程序,提示用戶輸入指定格式的日期。
void Main()
{
string datePrompt = "Please enter the date mm/dd/yyyy: ";
string invalidDateMessage = "Invalid date format, please use mm/dd/yyyy, for example you could type 01/07/1980.";
DateTime dateTime;
bool done = false;
while(!done)
{
string userInput = Prompt(datePrompt, Console.Out, Console.In);
done = ValidateAndParseDate(userInput, out dateTime, Console.Out, invalidDateMessage);
}
Console.WriteLine("I can now store {0} in a multi dimensional array!", dateTime.ToShortDateString());
}
string Prompt(string prompt, TextWriter writer, TextReader reader)
{
writer.Write(prompt);
string line = reader.ReadLine();
return line;
}
bool ValidateAndParseDate(string dateString, out DateTime dateTime, TextWriter writer, string errorMessage)
{
bool isValid = DateTime.TryParseExact(
dateString,
"MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime);
if(!isValid)
{
writer.WriteLine(errorMessage);
}
return isValid;
}
相關問題
- 1. 最好的格式來接收數據
- 2. 如何格式,從數據庫接收
- 3. 將數據從接收的JSON格式轉換爲JVectorMap格式
- 4. 接收來自調用gen_tcp套接字數據的特定量
- 5. 將接收到的數據格式化爲表格
- 6. 從MYSQL數據庫中收集ID,保存數組中的特定格式
- 7. 以特定格式顯示MySQL數據
- 8. 如何將數據格式化爲特定的JSON格式
- 9. 在PHP中接收的數組格式數據
- 10. 在特定接口上接收組播數據
- 11. 如何格式化數據特定格式
- 12. 使用php套接字以特定數據包格式發送數據
- 13. 接收來自特定源的UDP數據包
- 14. 多批量URB接收數據到特定的URB在USB LINUX
- 15. 如何從澤西島發送/接收avro格式的數據?
- 16. 接收數據格式html中的角度undefined
- 17. 快車4.0請求數據接收到的格式
- 18. 寫入後接收到的數據JSON文件JSON格式
- 19. 特定格式
- 20. excel宏從excel表格中獲取特定格式的數據
- 21. oracle特定列接受字符的特定格式
- 22. 以json格式和特定時間範圍從twitter收集數據
- 23. 只接收我的應用程序的特定格式的短信
- 24. 以特定方式從數據庫行格式化數組?
- 25. 創建具有特定格式的自定義數據類型
- 26. 深層鏈接與特定格式
- 27. python cgi腳本接收表格數據
- 28. 如何將以json格式接收的數據保存到數據庫中?
- 29. 在特定接收器處傳輸了多少數據
- 30. 使用libcurl從特定URL接收垃圾數據
windows forms? Web表單? (另外,你是不是隻是問這樣的問題?) –
你試過正則表達式嗎? – NSF