将.ToDateTime(’Datestring’)转换为日期所需的dd-MM-yyyy格式
我有日期的字符串,可以是任何日期格式,但我想将其转换为dd-MM-yyyy
格式。
我已经尝试了每个Convert.ToDatetime
选项,它只转换为系统格式。 我想要它转换dd-MM-yyyy
格式。
请回复。 提前致谢。
试试这个
DateTime dateTime = new DateTime(); dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDateString", "dd-MM-yyyy", CultureInfo.InvariantCulture));
这将使用您的Format
返回DateTime
尽管有很多答案,这是一个重复的答案,这里有一些可能的解决方案:
string formatted = date.ToString("dd-MM-yyyy");
要么
string formatted = date.ToString("dd MM yyyy");
此链接可能会为您提供更多格式和选项。
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");
开始了:
DateTime time = DateTime.Now; Console.WriteLine(time.Day + "/" + time.Month + "/" + time.Year);
//返回:22/05/2016