Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...