[英]Convert.ToDateTime('Datestring') to required dd-MM-yyyy format of date
I have string of Date which can be in any format of date but I wanted to convert it to dd-MM-yyyy
format. 我有Date的字符串,可以是任何格式的日期,但我想将其转换为
dd-MM-yyyy
格式。
I have tried every Convert.ToDatetime
option which converts only to the System format. 我已经尝试了每个
Convert.ToDatetime
选项,它只转换为系统格式。 I want it to convert dd-MM-yyyy
format. 我想要它转换
dd-MM-yyyy
格式。
Please reply. 请回复。 Thanks in Advance.
提前致谢。
Try this 尝试这个
DateTime dateTime = new DateTime();
dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDateString", "dd-MM-yyyy", CultureInfo.InvariantCulture));
This will return DateTime
with your Format
这将使用您的
Format
返回DateTime
Despite there being many answers and this being a duplicate answer, here are some possible solutions: 尽管有很多答案,这是一个重复的答案,这里有一些可能的解决方案:
string formatted = date.ToString("dd-MM-yyyy");
or 要么
string formatted = date.ToString("dd MM yyyy");
This link might help you with more formats and options. 此链接可能会为您提供更多格式和选项。
DateTime.ParseExact
has an overloaded method to accepts multiple formats, include (all)possible formats you receive and parse the string. DateTime.ParseExact
有一个重载方法,可以接受多种格式,包括(所有)可能接收的格式并解析字符串。 Once you get the valid DateTime
you could apply desired format in converting to string. 获得有效的
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");
Here we go: 开始了:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "/" + time.Month + "/" + time.Year);
//return: 22/05/2016 //返回:22/05/2016
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.