Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DECLARE @TargetDate DATETIME = GETDATE();
DECLARE @DateFormat VARCHAR(15);
SET @DateFormat = (SELECT FORMAT(@TargetDate, 'yyyymmdd_HHmmss')); -- HH is 24-hour format
SELECT @DateFormat;
DECLARE @TargetDate DATETIME = GETDATE();
DECLARE @DateFormat VARCHAR(15);
SET @DateFormat =
CONVERT(CHAR(4), YEAR(@TargetDate)) +
CASE WHEN MONTH(@TargetDate) < 10 THEN '0' + CONVERT(CHAR(1), MONTH(@TargetDate)) ELSE CONVERT(CHAR(2), MONTH(@TargetDate)) END +
CASE WHEN DAY(@TargetDate) < 10 THEN '0' + CONVERT(CHAR(1), DAY(@TargetDate)) ELSE CONVERT(CHAR(2), DAY(@TargetDate)) END +
'_' +
CASE WHEN DATEPART(HH, @TargetDate) < 10 THEN '0' + CONVERT(CHAR(1), DATEPART(HH, @TargetDate)) ELSE CONVERT(CHAR(2), DATEPART(HH, @TargetDate)) END +
CASE WHEN DATEPART(MI, @TargetDate) < 10 THEN '0' + CONVERT(CHAR(1), DATEPART(MI, @TargetDate)) ELSE CONVERT(CHAR(2), DATEPART(MI, @TargetDate)) END +
CASE WHEN DATEPART(SS, @TargetDate) < 10 THEN '0' + CONVERT(CHAR(1), DATEPART(SS, @TargetDate)) ELSE CONVERT(CHAR(2), DATEPART(SS, @TargetDate)) END
;
SELECT @DateFormat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.