Date and Time Functions Example: Handling Date and Time with
Microsoft Team's Messages
In this tutorial, we'll use the messages dataset from our Microsoft SQL Interview
Question which contains messages sent on Microsoft Teams.
Table: messages Sample Data
message_i
sender_id receiver_id content sent_date
d
08/16/2021
100 2520 6987 Send this out now!
00:00:00
08/10/2022
922 3601 4500 Get on the call
00:00:00
07/10/2022
819 2310 4500 What's the status on this?
00:00:00
06/14/2022
743 3601 8752 Let's take this offline
00:30:00
... ... ... ... ...
Maybe it was done by the 08/19/2022
990 2520 8520
automation process. 00:00:00
Getting the Current Date and Time in SQL
If you want to find out the current date and time, here's the functions that you can use:
CURRENT_DATE: Returns the current date.
CURRENT_TIME: Returns the current time without the date.
CURRENT_TIMESTAMP (or NOW()): Returns the current date and time.
Let's apply these functions onto the messages table:
SELECT
message_id,
sent_date,
CURRENT_DATE AS current_date,
CURRENT_TIME AS current_time,
CURRENT_TIMESTAMP AS current_timestamp
FROM messages
LIMIT 3;
Bear in mind, the dates and times you see in the results are based on when you run this
query. In this case, it's on 08/27/2023. This is why the dates might not match
the sent_date values from the table — they're showing the current date and time!
Here's the first 3 rows of the results:
message_id sent_date current_date current_time current_timestamp
08/16/2021 08/27/2023 08/27/2023
100 07:35:15.989933+00
00:00:00 00:00:00 07:35:15
08/10/2022 08/27/2023 08/27/2023
922 07:35:15.989933+00
00:00:00 00:00:00 07:35:15
07/10/2022 08/27/2023 08/27/2023
819 07:35:15.989933+00
00:00:00 00:00:00 07:35:15
Extracting Parts from Dates in SQL
This is pretty straightforward! 😉 The EXTRACT() function extracts a specific component (i.e.
year, month, day, hour, or minute) from a date or timestamp. You can also
use DATE_PART() for the same purpose.
SELECT
message_id,
sent_date,
EXTRACT(YEAR FROM sent_date) AS extracted_year,
DATE_PART('year', sent_date) AS part_year,
EXTRACT(MONTH FROM sent_date) AS extracted_month,
DATE_PART('month', sent_date) AS part_month,
EXTRACT(DAY FROM sent_date) AS extracted_day,
DATE_PART('day', sent_date) AS part_day,
EXTRACT(HOUR FROM sent_date) AS extracted_hour,
DATE_PART('hour', sent_date) AS part_hour,
EXTRACT(MINUTE FROM sent_date) AS extracted_minute,
DATE_PART('minute', sent_date) AS part_minute
FROM messages
LIMIT 3;