Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DATEDIFF working on yyyymmdd format SQL server

Tags:

sql

sql-server

Why the DATEDIFF accepts yyyymmdd format ? Isnt it only for yyyy-mm-dd format ?

The function DATEDIFF(datepart, start_date, end_date) is working fine when the dates are in yyyymmdd format e.g.

DATEDIFF(DAY, 20161201, 20161231);

It gives answer 30

and if you do DATEDIFF(DAY, 20161201, 20161231) + 1 -- end date inclusive

It gives 31

Thanks,

Aiden

like image 786
Aiden Avatar asked May 13 '26 18:05

Aiden


1 Answers

This can be a bit hard to tease out, but it is explained in the documentation, in the section "Supported String Literal Formats for date".

There are five sections on this (but the last two are API specific). The first section is affected by internationalization settings and has a bunch of different formats.

The second is the ISO 8601 format. I think the hyphenated format conflicts with the very last format in the first table ("yyyy dd mm" without the hyphens).

The final section has this informative line "A six- or eight-digit string is always interpreted as ymd". Hence, 'YYYYMMDD' is always interpreted correctly. Hence, this is the unambiguous format for date/time.

Note: Because the functions you are using expect dates, if the integer works, then it is converted to a date using its string representation. Normally, date constants should be in single quotes.

like image 95
Gordon Linoff Avatar answered May 15 '26 06:05

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!