C# 在SQL Server存储过程中格式化日期的最佳方法
这是我使用SQL Server的C# 在SQL Server存储过程中格式化日期的最佳方法,c#,asp.net,sql-server,C#,Asp.net,Sql Server,这是我使用SQL Server的date类型的示例数据 TglUnggah = 30/03/2014 我需要日期格式“dd/MM/yyyy” 我的存储过程 ALTER proc [dbo].[SP_ViewFile] AS BEGIN SELECT IdFile, IdAkses, NamaFile, Count, CONVERT(VARCHAR(10), TglUnggah, 103) AS TglUnggah, Ket
date
类型的示例数据
TglUnggah = 30/03/2014
我需要日期格式“dd/MM/yyyy”
我的存储过程
ALTER proc [dbo].[SP_ViewFile]
AS
BEGIN
SELECT
IdFile, IdAkses, NamaFile, Count,
CONVERT(VARCHAR(10), TglUnggah, 103) AS TglUnggah,
Keterangan, Role, Url
FROM
tbFile
END
在ASP.NET中运行此存储过程时,数据为30/03/2014
,但在detailview中,格式更改为30/03/2014 0:00:00
,无法更新
在SQL Server/Storage procedure/ASP.NET中使用格式
dd/MM/yyyy
的最佳方法是什么?以上都没有。尽可能使用DateTime。仅当需要向用户显示输出时才转换为格式化字符串。此时,您应该使用适合该用户文化的任何格式
DateTime的优点是易于操作,而且您不必担心在任何地方转换格式。DateTime实际上是一个包装器,用于包装特定日期后的刻度数(您不需要知道),因此DateTime对象没有固有的字符串表示形式(您需要知道)
在SQl server中,您可以使用以下步骤:
public static string ConvertDtFormat(string dateTimeString)
{
dateTimeString = dateTimeString.Trim();
while (dateTimeString.Contains(" "))
{
dateTimeString = dateTimeString.Replace(" ", " ");
}
if (dateTimeString == null || dateTimeString.Length == 0)
{
return string.Empty;
}
else
{
DateTime convertedDateTime = new DateTime();
string userDateFormat = HMS.DEFAULT_DATE_FORMAT;
try
{
if (userDateFormat.Trim().Contains("dd/MM/yyyy"))
convertedDateTime = DateTime.ParseExact(dateTimeString, format_dmy, CultureInfo.InvariantCulture,
DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
else if (userDateFormat.Trim().Contains("MM/dd/yyyy"))
convertedDateTime = DateTime.ParseExact(dateTimeString, format_mdy, CultureInfo.InvariantCulture,
DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
return convertedDateTime.ToString("MMM dd, yyyy hh:mm tt");
}
catch
{
return "Invalid DateTime";
}
}
}
此解决方案适用于希望在整个应用程序中以“dd/mm/yyyy”显示日期且不使用与时区相关的日期的用户。否则,您需要转换/强制转换要显示的数据 解决此问题的最佳方法是:-在之前编写的操作完成
Set Dateformat DMY
了解dateformat的基本规则:-
像
您可以按以下方式进行测试:
Set Dateformat dmy
Declare @date datetime = '10-06-2012'
select @date
它只需根据需要转换日期时间格式
< P> >另一件事要考虑。全球化时,您可能需要处理不同的时区,因此您可能希望使用日期-时间偏移来存储日期,以便存储UTC时间 @Ehsan这个问题似乎是关于如何设置在不同地方使用的日期格式,这就是我的答案。如果不是这样,OP完全有能力澄清自己。
Set Dateformat dmy
Declare @date datetime = '10-06-2012'
select @date