Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c# - DateTime.Parse() works on one machine but not the other

I'm using the Parse method to convert a string to a DateTime object:

requestRecord.TerminationDate = DateTime.Parse(reader.ReadString("Termination_Date"));

This code works on one machine but throws an exception on the other. I think the issue may perhaps be to do with the local culture. Looking at the taskbars on the two machines the one that throws the exception has the date as 01/12/2014 whereas the other shows 12/01/2014.

Is there some way that I can rewrite the above code so that it works on both machines regardless of the local DateTime culture?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess the culture settings differ on both machines. Try to supply the format. That explains why the date format is interpreted differently on both machines:

requestRecord.TerminationDate = DateTime.ParseExact
                                ( reader.ReadString("Termination_Date")
                                , "dd/MM/yyyy"
                                , CultureInfo.InvariantCulture
                                );

In this way, you are not depending on the machine and it's settings, but on the format you know.

Depending on what reader is, you might want to use reader.GetDateTime, which does all this for you already, for example SqlDataReader.GetDateTime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...