且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更新日期时间格式

更新时间:2023-02-12 20:21:39

是的,只需搜索日期 - 时间转换格式。



请点击我! [ ^ ]



我也是! [ ^ ]
Yes, just search for date-time conversion formats.

Click me![^]

me too![^]


您不必更改数据库中的数据。



如果数据库列数据类型是 DateTime ,则日期存储在 DateTime 中>格式不是字符串格式。以 DateTime 格式存储日期是正确的做法。月份优先或白天优先是显示选项,而不是您对日期存储方式的选择。 DateTime数据类型以内部格式存储日期,允许在从数据库中检索值后以多种不同方式格式化值。



检索日期时作为DateTime变量进入C#程序,它们可以通过C#应用程序以多种不同的方式进行格式化。以下是一些例子:

You do not have to change the data in the database.

If the database column data type is DateTime, then the dates are stored in the DateTime format not in a string format. It is the proper thing to do to store dates in a DateTime format. Month-first or day-first is a display choice not a choice you have on how the date is stored. The DateTime data type stores dates in an internal format that allows the value to be formatted in many different ways after it is retrieved from the database.

When the dates are retrieved into your C# program as a DateTime variable, they can be formatted in many different ways by your C# application. Here are some examples:
DateTime dtVar;
//
// Retrieve the date from database and put it into dtVar 
// then
Console.WriteLine(dtVar.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine(dtVar.ToString("MM-dd-yyyy"));
Console.WriteLine(dtVar.ToString("MM/dd/yyyy"));
Console.WriteLine(dtVar.ToString("dd-MM-yyyy"));
Console.WriteLine(dtVar.ToString("dd/MM/yyyy"));





如果你想将SQL中的日期作为字符串返回(我不推荐),那么你可以使用转换功能。以下是将同一日期转换为四个不同字符串的示例:



If you want to return the date from SQL as a string (which I do not recommend), then you can use the Convert function. Here is an example of converting the same date into four different strings:

select convert(varchar(10),reported_date,103), convert(varchar(10),reported_date,101),convert(varchar(10),reported_date,105),convert(varchar(10),reported_date,110)    from inventory_workorders



结果:


Results:

13/07/1992	07/13/1992	13-07-1992	07-13-1992
07/02/1995	02/07/1995	07-02-1995	02-07-1995
20/07/1993	07/20/1993	20-07-1993	07-20-1993





请注意,存储在数据库的DateTime列中的值已更改。使用C#中的格式字符串或SQL中的转换函数将日期格式从DateTime数据类型格式化为字符串格式。



Note that the values stored in the DateTime column in the database are not changed. The date is formatted from a DateTime data type to a string format using the format string in C# or the Convert function in SQL.