0

I'm trying to calculate the time remaining based on a target date. I have a target date of July 4, 2022 10:00:00 and I want to subtract that from today's date.

I first did SET @var_name = "July 4, 2022 10:00:00", followed by SELECT datediff(now(),@var_name) but it keeps returning a null value. Is there a way where I can have it display the number of days, hours and minutes remaining from the target date?

4
  • Format the date as YYYY-MM-DD SELECT datediff(now(),'2022-06-04 10:00:00') Commented Jun 3, 2022 at 1:25
  • what timezone is your target date? Commented Jun 3, 2022 at 1:42
  • There's a stackoverflow post about setting a datetime variable on sql server: stackoverflow.com/questions/7188222/…. You can check that out and see if it suits your question. Commented Jun 3, 2022 at 1:50
  • it's CST timezone Commented Jun 3, 2022 at 1:56

1 Answer 1

0

You can follow these steps:

  • format your string into the DATE format with STR_TO_DATE:

    STR_TO_DATE(@var_name, '%M %d, %Y %h:%i:%s')
    
  • get difference in seconds between dates with TIMESTAMPDIFF:

    TIMESTAMPDIFF(SECOND, NOW(), STR_TO_DATE(...))
    
  • transform seconds into time with SEC_TO_TIME:

    SEC_TO_TIME(TIMESTAMPDIFF(...))
    
  • extract hours, minutes and seconds from time using DATE_FORMAT:

    DATE_FORMAT(SEC_TO_TIME(...), '%H hours %i minutes %s seconds')
    
  • extract days separately as an integer division between hours and 24:

    HOUR(SEC_TO_TIME(...)) DIV 24
    

Check the full query followingly:

SET @var_name = "July 4, 2022 10:00:00";

WITH cte AS (
    SELECT SEC_TO_TIME(
                TIMESTAMPDIFF(SECOND, 
                              NOW(),
                              STR_TO_DATE(@var_name,
                                          '%M %d, %Y %h:%i:%s'))) AS seconds               )
SELECT CONCAT(HOUR(seconds) DIV 24,
              ' days ',
              DATE_FORMAT(seconds,
                          '%H hours %i minutes %s seconds'))
FROM cte

Try it here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.