Example of using the datediff function in Sqlserver

Source: Internet
Author: User
Tags datetime

The DATEDIFF () function returns the number of days between two dates.

Syntax

DATEDIFF (datepart, startdate, enddate)

The startdate AND enddate parameters are valid date expressions.

You need to know how many days the difference between a specified date and February 1, January 1. Therefore, you can use datediff to obtain:

The code is as follows: Copy code

Print datediff (day, '1-1-1-1 ', '2017-05-25 ')

The execution result is 4892, which is obviously an error value. Which day Does 1-1 correspond? Use dateadd to calculate:

The code is as follows: Copy code


Print dateadd (day,-4892, '2017-05-25 ')

The execution result is January 1. That is to say, the script cannot be expressed as 1-1-1 on January 1:

The code is as follows: Copy code


Print datediff (day, '2017-1-1 ', '2017-05-25 ')

The error message is as follows:

Reference content

Message 242, level 16, Status 3, 1st rows
Conversion from the varchar data type to the datetime data type generates a value out of the range.

0001-1-1 cannot be converted to datetime? For more information, see the SQL Server Documentation. The date range of the datetime type is January 1, January 1-9, 1753, December 31, 999. The datediff parameter is also subject to this restriction.

Why is the minimum datetime time January 1, 1753? Baidu:

Reference content

In the past, there were two calendars in the West: the ellipsis and the Gregorian calendar, which were different for a few days. When you use the ellipsis to transfer to the Gregorian calendar, you need to skip 10-13 days. Therefore, to store dates earlier than 1753, you must know which calendar is used and process the skipped 10 to 13 days. Most Western countries converted calendars in 1753.

Attached datdiff function parameters

Datepart Abbreviations
Year Yy, yyyy
Quarter Qq, q
Month Mm, m
Day of the year Dy, y
Day Dd, d
Week Wk, ww
Week Dw, w
Hours Hh
Minutes Mi, n
Seconds Ss, s
Millisecond MS
Subtle Mcs
Nanoseconds Ns

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.