[英]how to tell convert.todatetime that the input is in format dd-mm-yyyy
have written code that is supposed to 写了应该写的代码
take time and date input from the user 从用户那里获取时间和日期输入
and convert it to datetime format 并将其转换为日期时间格式
add some value to hrs and display it. 为hrs添加一些值并显示它。
My code works fine when the user gives input in the default format but when the user enters a date like dd-mm-yyyy instead of mm/dd/yyyy(default), it doesn't work. 当用户以默认格式输入时,我的代码工作正常但是当用户输入dd-mm-yyyy而不是mm / dd / yyyy(默认)之类的日期时,它不起作用。
How can I change the convert function to take care of this? 如何更改转换功能以解决此问题?
DateTime dt_calc = new DateTime();
dt_calc = Convert.ToDateTime(inputt);
To convert a date in the format dd-mm-yyyy
use: 要以
dd-mm-yyyy
格式转换日期,请使用:
var dateValue = DateTime.Parse("11/03/1989", new CultureInfo("en-GB", false));
But don't forget to add the System.Globalization
in the header or just do it inline: 但是不要忘记在标题中添加
System.Globalization
或者只是内联:
var dateValue = DateTime.Parse("11/03/1989", new System.Globalization.CultureInfo("en-AU", false));
Don't use Convert
- DateTime
has Parse
, TryParse
, ParseExact
and TryParseExact
methods that take a IFormatProvider
though for this simply using parse should work: 不要使用
Convert
- DateTime
有Parse
, TryParse
, ParseExact
和TryParseExact
方法,这些方法采用IFormatProvider
虽然这样只需使用解析应该工作:
DateTime dt_calc = DateTime.Parse(inputt);
If you would rather be safe, use `TryParse: 如果您想安全,请使用`TryParse:
DateTime dt_calc;
DateTime.TryParse(inputt, out dt_calc); // TryParse returns true if success, false if not
Have a look at this Code Project that extends the DateTime parsing capabilities. 看看这个扩展DateTime解析功能的代码项目 。 Alternatively there's a Natural Date Parser class on GitHub.
或者,在GitHub上有一个Natural Date Parser类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.