[英]How to Convert Date(from date time input field) to another date format in C#?
I have Date time input field from where I am taking date and converting it to another format, my code for that 我在从日期获取日期并将其转换为另一种格式的日期时间输入字段中
try
{
DateTime dt = dtiFrom.Value.Date;
string format = "DD-MM-YYYY"; // Use this format
MessageBox.Show(dt.ToString(format)); // here its shows result as DD-10-YYYY
DateTime dt1 = Convert.ToDateTime(dt.ToString(format)); // here Error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0."
}
catch (Exception ee)
{
MessageBox.Show(ee.Message, "Error Message!");
}
I am not able to convert date according to my format. 我无法根据我的格式转换日期。 please could any body help me in code or suggest me some code. 请任何人帮助我编写代码或向我推荐一些代码。 thanks in advance 提前致谢
Your format should be as follows: 您的格式应如下:
string format = "dd-MM-yyyy";
Casing is important with string formatting, you may think it strange that the month uses upper-case, but this is because lower case m
and mm
is used to represent minutes. 大小写对于字符串格式很重要,您可能会觉得月份使用大写字母很奇怪,但这是因为小写的m
和mm
用于表示分钟。
Note that the reason your output displays DD
and YYYY
is because any character that is not reserved as a format character will be outputted with no change. 请注意,您的输出显示DD
和YYYY
的原因是,任何未保留为格式字符的字符将被输出而不会发生任何变化。 Uppercase D
and Y
are not reserved which is why they display in the output, just as -
remains unchanged. 大写字母D
和Y
未被保留,这就是为什么它们在输出中显示的原因,就像-
保持不变。
If you wish to output reserved format characters then you can escape them using \\
. 如果您希望输出保留格式的字符,则可以使用\\
对其进行转义。
See here for a full list of date and time format values 请参阅此处以获取日期和时间格式值的完整列表
Date pattern format should be changed and better to use TryParseExact
instead of using Convert 日期模式格式应更改,最好使用TryParseExact
而不是使用Convert
DateTime dt = dtiFrom.Value.Date;
string format = "dd-MM-yyyy";
DateTime dt1 = new DateTime();
if (DateTime.TryParseExact(dt , format, null , DateTimeStyles.None, out dt1))
{
// you can use dt1 here
}
else
{
MessageBox.Show("Error Massage");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.