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

.net - How to compare two dates FORMATS for saving to DB

I want to compare two date formats and return "false" when two formats are not equal.

For example, I get two dates, 24/10/2012 (DD/MM/YYYY) and 2016/11/05 (YYYY/MM/DD)... in this case some function should return false because date formats are not equal.

I want a function thats returns false when the second format to compare not equal the SQL format (YYYY-MM-DD).

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You are asking a question (or two) which does not need to be answered.

Dates do not have a format Formats are how dates are displayed to humans. A date is simply a very large number like 636094492018399433L. It does not have a format.

I want a function thats returns false when the second format to compare not equal the SQL format (YYYY-MM-DD)

You really need not worry about the db format using the NET DB providers (e.g. OleDB, SQLite, SQL Server, MySQL). They all know how to properly store date data to a date column - its their job. If your columns are string, don't do that. If you want dates to act like dates, store them as dates.

Database docs bother to explain date formats for cases where you are entering data via a Shell interface from the keyboard, or perhaps importing data from a text/csv file. When using the NET DB Providers, the data format is an implementation detail.

Using dbCon As New MySQLConnection(mySQLConnStr)
    Using cmd As New MySqlCommand(SQL, dbCon)
        dbCon.Open()
        cmd.Parameters.Add("@p1", MySqlDbType.DateTime).Value = fromDate
        cmd.Parameters.Add("@p2", MySqlDbType.DateTime).Value = toDate

        cmd.ExecuteQuery
    End Using
End Using
  • specify the DbType as DateTime
  • pass it Date data.

To Store just the date, most DBs have a separate DbType.Date, but often you need to only pass the .Date portion:

cmd.Parameters.Add("@p2", MySqlDbType.Date).Value = toDate.Date

The NET DB Providers all Know Things, like how to take a NET Date and save it to the database they were built for, and do so in a format it can parse/read back from.


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

...