SQL Server: Get Current Date & Time

Retrieving the current date and time is a fundamental operation in SQL Server, essential for logging, data tracking, and reporting. Whether you need a simple timestamp for everyday use or require high-precision time tracking for financial transactions, SQL Server provides built-in functions that cater to different levels of accuracy.

In this guide, I’ll demo some ways to obtain date and time values in SQL Server with an added tip on formatting the output. Hope it’s useful for you!


1. Get Current Date & Time in SQL Server

The GETDATE() function returns the current date and time with millisecond precision, making it suitable for most standard applications.

-- Get current date and time
SELECT GETDATE() AS CurrentDateTime;

2. Get High-Precision Date & Time

For applications that require more precise time tracking, SYSDATETIME() provides nanosecond-level accuracy.

-- Get current date and time with extra precision
SELECT GETDATE() AS CurrentDateTime;
Get Current Date Time SQL Server

3. Customize Output of Date & Time Value

If you need to display the date in a specific format, use the FORMAT() or CAST()/CONVERT() functions to customize its appearance.

-- Get current date in custom format 
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS FormattedDate;

-- Get current date small date time example
SELECT CAST(GETDATE() AS SMALLDATETIME) AS FormattedDate;
SQL Server Format Date Example
Formatting current date time example

Wrapping Up

Use GETDATE() for general timestamp needs and SYSDATETIME() for high-precision applications. Formatting functions like FORMAT() and CAST() help convert and return the current date/time as different datatypes.

Summary of Functions:
FunctionPrecision LevelBest Use Case
GETDATE()MillisecondsGeneral logging, reporting
SYSDATETIME()NanosecondsHigh-precision tracking (e.g., financial transactions)



Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts
Categories
Tags

Always On Availability Groups (AAG) (4) AWS (4) AWS Redshift (6) Certificates & Encryption (3) Change Data Capture (CDC) (2) Database Admin (72) Database Backups & Recovery (14) Database Mirroring (2) Deleting Data (1) Error Messages (5) Git Commands (6) Importing & Exporting Data (2) Linked Servers (3) Linux Admin (2) Logging & Monitoring (1) Measuring Databases (10) Microsoft Patching (2) MySQL (4) Postgres (6) PowerShell Scripts (1) SQL Server Agent (5) SQL Server Database Files (1) SQL Server Data Types (2) SQL Server Management Studio (SSMS) (15) SQL Server Network Connectivity (3) SQL Server on Linux (1) SQL Server Patching (2) SQL Server Performance (6) SQL Server Permissions (2) SQL Server Processes (SPIDs) (7) SQL Server Replication (2) SQL Server Scripts (13) Windows Admin (21) Windows Authentication (2) Windows Automation (1) Windows Events (2) Windows Firewall (4) Windows Subsystem for Linux (WSL) (18)