最简单的方式来创建一个月的第一天的日期,给定另一个日期 [英] Simplest way to create a date that is the first day of the month, given another date

查看:171
本文介绍了最简单的方式来创建一个月的第一天的日期,给定另一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL Server中,基于另一个日期时间,最简单/最干净的方法是使代表本月第一个的日期时间?例如,我有一个变量或列与2005年3月3日14:23,我想获得2005年3月1日00:00(作为datetime,而不是varchar)

In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)

推荐答案

Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)

要在列上运行,请将GetDate()替换为列名。

To run this on a column, replace GetDate() with your column name.

该代码的技巧是使用DateDiff。 DateDiff返回一个整数。第二个参数(0)表示SQL Server中的0日期,即1900年1月1日。因此,datediff计算从1900年1月1日起的整数月数,然后将该月数添加到1900年1月1日。净效果是删除日期时间值的日期(和时间)部分。

The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.

这篇关于最简单的方式来创建一个月的第一天的日期,给定另一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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