尝试以与字符串不同的格式将字符串转换为日期时间
所以我必须将(MM-dd-yyyy)格式的日期转换为(dd-MMM-yyyy)。我最终做的是这样的...
string strProvisionalDate = "04-22-2001";
string strFormat = "MM-dd-yyyy";
DateTime dtProvisional;
DateTime.TryParseExact(strProvisionalDate, strFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtProvisional);
string strProvisionalDateConverted = dtProvisional.ToString("dd-MMM-yyyy");
string strFormatConverted = "dd-MMM-yyyy";
DateTime dtProvisionalConverted;
DateTime.TryParseExact(strProvisionalDateConverted, strFormatConverted, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtProvisionalConverted);
基本上,我将其转换为 DateTime,将其转换为我想要的格式的字符串,然后将其转换回 DateTime。它有效,但我很好奇是否有更好的方法来做到这一点......它看起来不太优雅。
编辑:事实证明,在这个 dtProvisional 和 dtProvisionalConverted 最终是相同的。所以我的新问题是,如何将 MM-dd-YYYY 格式的字符串转换为 dd-MMM-yyyy 格式的日期时间? dtProvisional 将进入 SQL 数据库,并且必须采用日期格式。
So I had to convert a date in the format of (MM-dd-yyyy) to (dd-MMM-yyyy). What I ended up doing was this...
string strProvisionalDate = "04-22-2001";
string strFormat = "MM-dd-yyyy";
DateTime dtProvisional;
DateTime.TryParseExact(strProvisionalDate, strFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtProvisional);
string strProvisionalDateConverted = dtProvisional.ToString("dd-MMM-yyyy");
string strFormatConverted = "dd-MMM-yyyy";
DateTime dtProvisionalConverted;
DateTime.TryParseExact(strProvisionalDateConverted, strFormatConverted, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtProvisionalConverted);
Basically, I converted it to DateTime, converted that to a string in the format I wanted, then converted that back to DateTime. It works, but I was curious to ask if there was a better way to do this...it doesn't seem very elegant.
edit: Turns out, in this dtProvisional and dtProvisionalConverted end up being the same. So my new question would be, how can I convert a string in the format of MM-dd-YYYY to a DateTime in the format of dd-MMM-yyyy? dtProvisional is going into a SQL database, and it has to be in Date format.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DateTime 对象不将日期/时间存储为格式,而是将其存储为自纪元以来的刻度数。作为对象,dtProvisional 和 dtProvisionalConverted DateTime 之间应该没有区别(它们的实际值应该相同)。使用字符串格式功能将日期时间输出到字符串时,始终可以更改字符串格式。
请参阅此MSDN 文章的备注部分。
我这将正确格式化您的日期以进行输出:
String.Format("{0:dd-MMM-yyyy}", dt);
The DateTime object doesn't store date/time as a format, it stores it as a number of ticks since the epoch. There should be no difference between dtProvisional and dtProvisionalConverted DateTime as object (their undelying value should be the same). The string format can always be changed when outputting the DateTime to a string using the String Format functionality.
See the remarks section on this MSDN article.
I this will format your date correctly for outputting:
String.Format("{0:dd-MMM-yyyy}", dt);
正在类似线路上搜索详细信息......
这对我有用......
was searching details on similar line....
that worked for me....