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
152 views
in Technique[技术] by (71.8m points)

c# - Difference between DateTime formats in Database and Dataset

I have a datetime column in my SQL Server table which contains value like:

2021-01-27 00:00:00.000

When I fetch values from table my DataSet for this certain field is now like

27.1.2021. 0:00:00

I would like to convert this value to another format but what I get is exception

Additional information: String was not recognized as a valid DateTime.

Code:

DateTime dt = DateTime.ParseExact(row["DO_Date"].ToString(), "DD.m.YYYY. H:mm:ss", CultureInfo.InvariantCulture);

Why there is difference between value in table and then later in dataset? How to determine correct format and convert given datetime?

question from:https://stackoverflow.com/questions/65908885/difference-between-datetime-formats-in-database-and-dataset

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

1 Reply

0 votes
by (71.8m points)

row["DO_Date"].ToString() returns a string which depends on your local system regional datetime setting. Try doing the following:

DateTime dt = DateTime.ParseExact(row["DO_Date"].ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

In other words - force the source format to be the same as the one you are trying to convert to.

There is a simpler way though:

DateTime dt = (DateTime)row["DO_Date"]

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

...