Home Building Dates
Post
Cancel

Building Dates

Building Dates

  • Building a Date

    1
    2
    3
    
          SELECT
              GETDATE() AS DateTime_LTz,
              GETUTCDATE() AS DateTime_UTC;
    
    1
    2
    3
    
          SELECT
              SYSDATETIME() AS DateTime2_LTz,
              SYSUTCDATETIME() AS DateTime2_UTC;
    
  • Breakding down a date

    1
    2
    3
    4
    5
    6
    7
    8
    
          DECLARE
              @SomeDate DATETIME(3) = '2019-03-01 08:17:19.332';
    
          SELECT YEAR(@SomeDate);
    
          SELECT MONTH(@SomeDate);
    
          SELECT DAY(@SomeDate);
    

    The above sql statements returns YEAR = 2019, MONTH =3, and DAY = 1

  • Parsing Dates with Date Parts

    • Parts
      • Year / Month / Day
      • Day of year
      • Day of week
      • Week of year
      • ISO week of year
      • Minute / Second
      • Millisecond / Nanosecond
    • Functions
      • DATEPART()
        1
        2
        
              SELECT
                  DATEPART(YEAR, @dt) AS TheYear;
        
      • DATENAME()
        1
        2
        
              SELECT
                  DATENAME(MONTH, @dt) AS TheMonth;
        
  • Adding and Subtracting dates

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
          DECLARE
              @SomeTime DATETIME2(7) = '1992-07-14 14:49:36.2294852';
    
          SELECT 
              DATEADD(DAY, 1, @SomeTime) AS NextDay,
              DATEADD(Day, -1, @SomeTime) AS PriorDay;
    
          SELECT 
              DATEADD(HOUR, -3, DATEADD(DAY,-4, @SomeTime)) AS Minus4Day3Hours;
    
  • Comparing Dates

    1
    2
    3
    4
    5
    6
    7
    8
    
          DECLARE
              @StartTime DATETIME2(7) = '2012-03-01 14:29:36',
              @EndTime DATETIME2(7) = '2012-03-01 18:00:00';
    
          SELECT
              DATEDIFF(SECOND, @StartTime, @EndTime) AS SecondsElapsed,
              DATEDIFF(MINUTE, @StartTime, @EndTIme) AS MinutesElapsed,
              DATEDIFF(HOUR, @StartTime, @EndTime) AS HoursElapsed;
    

Formatting Dates For Reporting

  • Formatting Functions

    • CAST()
    • CONVERT()
    • FORMAT()
  • The CAST() function

    • Useful for converting one data type to another data type, including date types
    • No control over formatting dates to strings
    • ANSI SQL Standard, meaning any relational and most non-relational databses have this function
  • Using the CAST() function

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
          DECLARE
              @SomeDate DATETIME2(3) = '1991-06-04 08:00:09',
              @SomeString NVARCHAR(30) = '1991-06-04 08:00:09',
              @OldDateTime DATETIME = '1991-06-04 08:00:09';
    
    
          SELECT
              CAST(@SomeDate AS NVARCHAR(30)) AS DateToString,
              CAST(@SomeString AS DATETIME2(3)) AS StringToDate,
              CAST(@OldDateTime AS NVARCHAR(30)) AS OldDateToString;
    
  • The CONVERT() function

    • Useful for converting one data type to another data type, including date types
    • Some control over formattting from dates to strings using the style parameter
    • Specific to T-SQL
    1
    2
    3
    4
    5
    6
    7
    8
    
          DECLARE 
              @SomeDate DATETIME2(3) = '1793-02-21 11:13:19.033';
    
          SELECT
              CONVERT(NVARCHAR(30), @SomeDate,0) AS DefaultForm,
              CONVERT(NVARCHAR(30), @SomeDate,1) AS UD_mdy,
              CONVERT(NVARCHAR(30), @SomeDate, 101) AS US_mdyyyy,
              CONVERT(NVARCHAR(30), @SomeDate, 120) AS ODBC_sec;
    
    • Sample CONVERT() styles

      Style CodeFormat
      1 / 101United States m/d/y
      3 / 103British/French d/m/y
      4 / 104German d.m.y
      11 / 111Japanese y/m/d
      12 / 112ISO Standard yyyymmdd
      20 / 120ODBC Standard (121 for ms)
      126ISO8601 yyyy-mm-dd hh:mi:ss.mmm
      127yyyy-mm-ddThh:mi:ss.mmmZ
  • The FORMAT() function

    • Useful for formatting a date or number in a particular way for reporting
    • Much more flexibility over formatting from dates to strings than either CAST() or CONVERT()
    • Specific to T-SQL
    • Can be slower as you process more rows
    1
    2
    3
    4
    5
    6
    7
    8
    
          DECLARE 
              @SomeDate DATETIME2(3)  = '1793-02-21 11:13:19.033';
    
          SELECT
              FORMAT(@SomeDate, 'd', 'en-US') AS US_d,
              FORMAT(@SomeDate, 'd', 'de-DE') AS DE_d,
              FORMAT(@SomeDate, 'D', 'de-DE') AS DE_D,
              FORMAT(@SomeDate, 'yyyy-MM-dd') AS yMd,
    
  • Working With Calendar Tables

    A calendar table is a permanent table containing a list of dates and various components of those dates.

    1
    2
    
          SELECT *
          FROM dbo.Calendar;
    
  • Contents of a calendar table

    image

  • Building a Calendar Table

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
          CREATE TABLE dbo.Calendar (
              DateKey INT NOT NULL,
              [Date] DATE NOT NULL,
              [Day] TINYINT NOT NULL,
              DayOfWeek TINYINT NOT NULL,
              DayName VARCHAR(10) NOT NULL,
              ....
          )
    
    
          SELECT
              CAST(D.DateKey AS INT) AS DateKey,
              D.[DATE] AS [DATE],
              CAST(D.[day] AS TINYINT) AS [day],
              CAST(d.[dayofweek] AS TINYINT) AS [DayOfWeek],
              CAST(DATENAME(WEEKDAY, d.[Date]) AS VARCHAR(10)) AS [DayName],
              ....
    
  • Using a Calendar Table

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
          SELECT
              c.Date
          FROM dbo.Calendar c
          WHERE
              c.MonthName = 'April'
              AND c.DayName = 'Saturday'
              AND c.CalendarYear = 2020
          ORDER BY 
              c.Date;
    
  • A quick note on APPLY()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
          SELECT
              FYStart = DATEADD(MONTH, -6,
                          DATEADD(YEAR, 
                              DATEDIFF(YEAR, 0,
                                  DATEADD(MONTH, 6, d.[date])), 0)),
                
              FiscalDayOfYear = DATEDIFF(DAY,
                                  DATEADD(MONTH, -6, 
                                      DATEADD(YEAR,
                                          DATEDIFF(YEAR, 0,
                                              DATEADD(MONTH, 6, d.[date])), 0)), d.[Date]) + 1,
    
              FiscalWeekOfYear = DATEDIFF(WEEK, 
                                      DATEADD(MONTH, -6,
                                          DATEADD(YEAR,
                                              DATEDIFF(YEAR,0,
                                                  DATEADD(MONTH,6,d.[date])), 0)), d.[Date]) +1
          FROM dbo.Calendar d;
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
          SELECT
              fy.FYStart,
              FiscalDayOfYear = DATEDIFF(DAY, fy.FYStart, d.[Date])+1,
              FiscalWeekOfYear = DATEDIFF(WEEK, fy.FYStart, d.[Date]) +1
          FROM dbo.Calendar d
          CROSS APPLY
          (
              SELECT FYStart = DATEADD(MONTH, -6,
                                  DATEADD(YEAR,
                                      DATEDIFF(YEAR,0,
                                          DATEADD(MONTH, 6, d.[date])),0))
          ) fy;
    
This post is licensed under CC BY 4.0 by the author.