如何仅从SQL Server DateTime数据类型返回日期 [英] How to return only the Date from a SQL Server DateTime datatype

查看:105
本文介绍了如何仅从SQL Server DateTime数据类型返回日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SELECT GETDATE()

返回值: 2008-09-22 15:24:13.790

我希望该日期部分没有时间部分: 2008-09-22 00:00:00.000

I want that date part without the time part: 2008-09-22 00:00:00.000

如何获得?

推荐答案

SQL Server 2008 及更高版本上,您应转换到目前为止:

On SQL Server 2008 and higher, you should CONVERT to date:

SELECT CONVERT(date, getdate())

在旧版本上,您可以执行以下操作:

On older versions, you can do the following:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))

例如

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

请给我

2008-09-22 00:00:00.000

优点:


  • 不需要 varchar <-> datetime 转换

  • 无需考虑 loc ale

  • No varchar<->datetime conversions required
  • No need to think about locale

Michael

使用此变体: SELECT DATEADD(dd ,DATEDIFF(dd,0,getdate()),0)

select getdate()

SELECT DATEADD(hh, DATEDIFF(hh, 0, getdate()), 0)
SELECT DATEADD(hh, 0, DATEDIFF(hh, 0, getdate()))

SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, getdate()))

SELECT DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
SELECT DATEADD(mm, 0, DATEDIFF(mm, 0, getdate()))

SELECT DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
SELECT DATEADD(yy, 0, DATEDIFF(yy, 0, getdate()))

输出:

2019-04-19 08:09:35.557

2019-04-19 08:00:00.000
4763-02-17 00:00:00.000

2019-04-19 00:00:00.000
2019-04-19 00:00:00.000

2019-04-01 00:00:00.000
1903-12-03 00:00:00.000

2019-01-01 00:00:00.000
1900-04-30 00:00:00.000

这篇关于如何仅从SQL Server DateTime数据类型返回日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆