日期格式转换时出错 [英] DATE FORMAT Error while converting

查看:88
本文介绍了日期格式转换时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调试时收到错误,说明FormaException未处理。附加信息:String未被识别为有效的DateTime。



以下是我的代码:



string iString = df.cmbColumns.SelectedIndex.ToString();

DateTime oDate = DateTime.ParseExact(iString,{0:dd / MM / yyyy hh:mm:tt},null);

MessageBox.Show(oDate.ToString());

I'm getting an error while debugging stating "FormaException was unhandled". Additional information: String was not recognized as a valid DateTime.

Below is my code:

string iString = df.cmbColumns.SelectedIndex.ToString();
DateTime oDate = DateTime.ParseExact(iString, "{0:dd/MM/yyyy hh:mm:tt}", null);
MessageBox.Show(oDate.ToString());

推荐答案

你的格式字符串错了,试试这个:

Your format string is wrong, try this:
DateTime oDate = DateTime.ParseExact(iString, "dd/MM/yyyy hh:mm:tt", null);



{0:dd / MM / yyyy hh:mm:tt}在String.Format中用来表示哪个参数如何格式化。


{0:dd/MM/yyyy hh:mm:tt} is used in String.Format to denote which parameter how to format.


要添加到Tomas所说的,不仅是你的格式字符串错误,而是使用DateTime。作为字符串的单个整数值的ParseExact也不起作用。

由于SelectedIndex只会返回在整数值中,您尝试转换的字符串永远不会是有效日期。

我建议如果您想在组合框中使用日期值,请使用DateTime值加载它并使用而不是SelectedValue属性。
To add to what Tomas says, not only is your format string wrong, but using DateTime.ParseExact on a single integer value as a string isn't going to work either.
And since SelectedIndex will only ever return an integer value, the string you are trying to convert will never be a "valid date".
I would suggest that if you want date values in a combobox, you load it with DateTime values and use the SelectedValue property instead.


这个问题每天被问到多次,就像问这个问题的其他人一样,你没有告诉我们最重要的信息部分....在iString中。因为iString中的内容不是ParseExact要求的格式。这正是错误信息告诉你的。



我唯一能想到的是你不知道日期格式字符串是什么。例如,tt是AM或PM,所以你期待像
这样的日期


22/01/2016 01:26:PM



您的日期实际上不太可能是这种格式,也许您的意思是ss而不是tt。



自定义日期和时间格式字符串 [ ^ ]



除非您发布iString中的内容,否则任何人都无法告诉您。
This question is asked multiple times a day, and like everyone else that asks this question you haven't told us the most important part of information....what is in iString. Because what is in iString isn't in the format that your ParseExact is asking for. That's exactly what the error message is telling you.

The only thing I can think of is that you don't know what the date format strings are. "tt", for example, is "AM" or "PM" so you are expecting a date like

22/01/2016 01:26:PM

It's unlikely your date is actually in this format, maybe you meant "ss" instead of "tt".

Custom Date and Time Format Strings[^]

Unless you post what is in iString there really is nothing anyone can tell you.


这篇关于日期格式转换时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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