将yyyy.mm.dd转换为yyyy-mm-dd c# [英] convert yyyy.mm.dd to yyyy-mm-dd c#

查看:121
本文介绍了将yyyy.mm.dd转换为yyyy-mm-dd c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此代码,但返回错误。我可以使用toString()方法,但我希望结果在DateTime中







 DateTime dt = DateTime.ParseExact(  2015.05.05  MM-dd-yyyy,System.Globalization.CultureInfo.InvariantCulture); 

解决方案

问题是格式字符串'MM-dd-yyyy'没有达到值'2015.05 .05'并且对于那个ParseExact将抛出一个无效值的异常...你可以尝试TryParseExact,但是你会得到的唯一的瘦,不会抛出异常,但会返回一个布尔值 - 但仍然没有有效的DateTime对象...

您需要做的是分两步完成......

1.根据格式将字符串转换为有效的DateTime对象:

 DateTime oDT = DateTime.ParseExact(  2015.05.05  yyyy.MM.dd,System.Globalization.CultureInfo.InvariantCulture); 



2.根据需要格式化DateTime对象:

  string  szDT = oDT.ToString(  MM-dd-yyyy); 





https://dotnetfiddle.net/VJ61Nu [ ^ ]






点击这里 https://msdn.microsoft.com/en-us/library/w2sa9yss(v = vs.110)的.aspx [ ^ ]



您也可以这样编码

 DateTime dt =  new  DateTime( 2015  05  05 ); 
DateTime result = DateTime.ParseExact(dt.ToString( MMM / dd / yyyy ), MM / dd / yyyy,CultureInfo.InvariantCulture);





如果这样可以解决您的问题,请将其标记为答案。 : - )


与string.replace?类似于:

  string  str1 =    2015.05.05; 
string str2 = str1.Replace( - );


I try with this code, but its return error. I can use toString() method, but i want that result been in DateTime



DateTime dt = DateTime.ParseExact("2015.05.05", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

解决方案

The problem is that the format string 'MM-dd-yyyy' does not fir to the value '2015.05.05' and for that ParseExact will throw an exception of invalid value... You may try TryParseExact, but the only thin you will get, that no exception will be thrown, but a boolean value will be returned - but still no valid DateTime object...
What you have to do is do it in two steps...
1. Turn string into valid DateTime object according its format:

DateTime oDT = DateTime.ParseExact("2015.05.05", "yyyy.MM.dd", System.Globalization.CultureInfo.InvariantCulture);


2. Format that DateTime object according your needs:

string szDT = oDT.ToString("MM-dd-yyyy");



https://dotnetfiddle.net/VJ61Nu[^]


Hi,

check here https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx[^]

You can code like this also

DateTime dt = new DateTime(2015, 05, 05);
DateTime result = DateTime.ParseExact(dt.ToString("MMM/dd/yyyy"), "MM/dd/yyyy", CultureInfo.InvariantCulture);



If this solves your problem, then please mark it as answer. :-)


What about String.Replace? Something like:

string str1 = "2015.05.05";
string str2 = str1.Replace(".", "-");


这篇关于将yyyy.mm.dd转换为yyyy-mm-dd c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆