[已解决]更改系统的DateTime格式后将字符串转换为DateTime的问题 [英] [Solved] Problem converting string to DateTime after changing System's DateTime format

查看:82
本文介绍了[已解决]更改系统的DateTime格式后将字符串转换为DateTime的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

将字符串转换为DateTime时遇到问题.
我是这样的:

Hello All,

I am facing a problem while converting a string to DateTime.
I am doing it like this:

DateTime dt = Convert.ToDateTime(strDate)


我得到了正确的结果.

但是,一旦我将系统的短日期格式从"MM/dd/yy"更改为"dd-MMM-yy",我就会收到错误消息,因为字符串不是有效的DateTime格式.

我调试并检查了strDate的值,它是有效的DateTime格式.
谁能告诉我如何处理系统的DateTime格式的更改.

附加代码:
我将我的DateTimePicker值保存为字符串到数据库,然后在窗体加载时将相同的值分配给我的DateTimePicker .....但是,如果在两者之间更改系统的日期时间格式,我会报错


I was getting correct result.

But as soon as I changed my system''s short date format from ''MM/dd/yy'' to ''dd-MMM-yy'', I am getting an error as "string is not a valid DateTime format.

I debugged and checked value of strDate and it is a valid DateTime format.
Can anyone tell me how can I handle this change in system''s DateTime format.

Additional Code:
I am saving my DateTimePicker value as a string to database and then on form load i am assigning same value to my DateTimePicker..... but if in between i change my system''s datetime format i am getting error

//ScheduleEveryStart is a string which is getting saved in to database
clsGlobal.Configuration.ScheduleEveryStart = Convert.ToString(dtpStart.Value);

//load form code
dtpStart.Value = (clsGlobal.Configuration.ScheduleEveryStart == "") ? System.DateTime.Now : Convert.ToDateTime(clsGlobal.Configuration.ScheduleEveryStart);



谢谢,
Nagendra.



Thanks,
Nagendra.

推荐答案

尝试此链接

try this link

ClickHere[^]



您是否尝试过DateTime.Parse方法.从理论上讲,该方法应注意识别正确的格式-
http://msdn.microsoft.com/en -us/library/1k1skd40.aspx [ ^ ]
问候
Hi,
have you tried DateTime.Parse method. Theoretically, the method should take care in recognizing the right format - http://msdn.microsoft.com/en-us/library/1k1skd40.aspx[^]
Regards


如果您不需要时间,可以像这样调用代码.

If you dont need the time you can call your code like this.

string[] strs = s.Split('' '');

if (strs.Length > 1) {
   DateTime dt = Convert.ToDateTime(strs[0]);
}



这个想法是消除导致转换错误的时间.

或尝试这种方法



The idea is strip out the time that causing the conversion error.

OR try this approach

string dateString = "01/31/2011";
string pattern = "d/M/yyy h:mm:ss tt"; //more info below
DateTime parsedDate = DateTime.Now;

if (DateTime.TryParseExact(dateString, pattern, null, DateTimeStyles.None, out parsedDate)){
   //parsedDate
   //ready to be used
   //....
}



使用模式 [



Pattern to use[^]


Hope this works.


这篇关于[已解决]更改系统的DateTime格式后将字符串转换为DateTime的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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