Check if time is passed – Python

In this tutorial, you will learn how to check if the time is passed in Python.

First, we will get the future time in UTC. In order to get this, first we will get the current time in UTC.

Then we will add 24 hours in it.

After that, we will get time_struct object from it. This will be used to get the Unix timestamp.

Then we will the Unix timestamp using the time_struct object.

Same can be done for getting the current time in UTC but without adding 24 hours in it.

delta is the difference between future Unix timestamp and current one.

Then we will convert the seconds into minutes by dividing it to 60 since each minute has 60 seconds.

And again dividing that to 60 since each hour has 60 minutes. This will return the number of hours since the time is passed.

Finally, we will check if the delta is less than or equal to zero. If it is, it means that the time is passed. If not, it means that the time is not passed yet.

from datetime import datetime, timezone, timedelta
import time

future_time = datetime.now(timezone.utc)		# current datetime in UTC
future_time = future_time + timedelta(hours=24)	# current time + 24 hours
future_time = future_time.timetuple()			# instance of time.struct_time
future_time = time.mktime(future_time)			# Unix timestamp

current_time = datetime.now(timezone.utc)		# current datetime in UTC
current_time = current_time.timetuple()			# instance of time.struct_time
current_time = time.mktime(current_time)		# Unix timestamp

delta = future_time - current_time				# difference between future datetime and current datetime (in seconds)
delta = delta / 60 / 60							# convert seconds into hours

if delta <= 0:								   # check if the time is passed
	print("Time passed")
else:
	print("Time not passed")

You can check the real-world example of this in the URL shortener app we created in Python.

Convert date format to another – PHP, HTML

In this tutorial, we are going to teach you how to convert the date format from one to another using Javascript. We will also be adding, subtracting date by days.

Video tutorial

First, we will create a form to get the source and destination format from the user.

<form method="POST" onsubmit="return generateCode(this);">
    
    <div>
        <select name="source_format">
            <option value="">Enter source format</option>
            <option value="timestamp">Timestamp (123456789)</option>
            <option value="Y-m-d">Y-m-d (2020-08-30)</option>
            <option value="Y-m-d H:i:s">Y-m-d H:i:s (2020-08-30 14:30:18)</option>
            <option value="Y-m-d h:i:s A">Y-m-d h:i:s A (2020-08-30 02:30:18 PM)</option>
            <option value="Y-m-d h:i:s a">Y-m-d h:i:s a (2020-08-30 02:30:18 pm)</option>
            <option value="d M, Y">d M, Y (30 August, 2020)</option>
            <option value="D">D (Mon, Tue)</option>
        </select>
    </div>

    <div style="margin-top: 10px;">
        <select name="destination_format">
            <option value="">Enter destination format</option>
            <option value="timestamp">Timestamp (123456789)</option>
            <option value="Y-m-d">Y-m-d (2020-08-30)</option>
            <option value="Y-m-d H:i:s">Y-m-d H:i:s (2020-08-30 14:30:18)</option>
            <option value="Y-m-d h:i:s A">Y-m-d h:i:s A (2020-08-30 02:30:18 PM)</option>
            <option value="Y-m-d h:i:s a">Y-m-d h:i:s a (2020-08-30 02:30:18 pm)</option>
            <option value="d M, Y">d M, Y (30 August, 2020)</option>
            <option value="D">D (Mon, Tue)</option>
        </select>
    </div>

    <input type="submit" value="Generate Code" />

    <p id="output" style="display: none;"></p>
</form>

Then we will create a Javascript function that will write the PHP code to echo the date by converting it from source format to destination format.

<script>
    function generateCode(form) {

        var sourceFormat = form.source_format.value;
        var destinationFormat = form.destination_format.value;

        var html = "";
        var dateHtml = "";
        if (sourceFormat == "timestamp" && destinationFormat == "timestamp") {
            dateHtml = `echo $timestamp_value;`;
        } else if (sourceFormat == "timestamp") {
            dateHtml = `echo date('` + destinationFormat + `', $timestamp_value);`;
        } else if (destinationFormat == "timestamp") {
            dateHtml = `echo strtotime($date_value);`;
        } else {
            dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value));`;
        }
        html += `&lt;?php<br />
            <span style='margin-left: 1em;'>&emsp;` + dateHtml + `</span><br />
        ?>`;
        
        document.getElementById("output").innerHTML = html;
        document.getElementById("output").style.display = '';

        return false;
    }
</script>

The resulting output will be displayed in a paragraph. Right now we are displaying a dropdown to select a date format. But what if the user wants to write a custom format ? So we will create 2 more fields for writing custom format for source and destination.

<input type="text" style="margin-left: 10px;" name="source_format_custom" placeholder="Custom source format" />

<input type="text" style="margin-left: 10px;" name="destination_format_custom" placeholder="Custom destination format" />

Then we need to update our custom date format variables if these fields have some value.

var sourceFormat_custom = form.source_format_custom.value;
if (sourceFormat_custom != "") {
    sourceFormat = sourceFormat_custom;
}

var destinationFormat_custom = form.destination_format_custom.value;
if (destinationFormat_custom != "") {
    destinationFormat = destinationFormat_custom;
}

Add/subtract from the date

Now we need to add or subtract months, years, or days from the new date format. For this, we will create 2 dropdowns to check if the user wants to add or subtract. And second to check if he wants to add/subtract days, months, or years.

<p style="text-align: center;">Add / subtract date (optional)</p>

<div>
    <select name="addsubtract_date">
        <option value="">None</option>
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
    </select>

    <select name="addsubtract_datetype">
        <option value="years">Years</option>
        <option value="months">Months</option>
        <option value="days">Days</option>
        <option value="hours">Hours</option>
        <option value="minutes">Minutes</option>
        <option value="seconds">Seconds</option>
    </select>
</div>

<input type="number" placeholder="Enter value" name="addsubtract_datevalue" />

Now when the form is submitted, we need to get the values of both these dropdowns.

var addsubtractdate = "";
if (form.addsubtract_date.value == "add") {
    addsubtractdate = "'+ " + form.addsubtract_datevalue.value + " " + form.addsubtract_datetype.value + "'";
} else if (form.addsubtract_date.value == "subtract") {
    addsubtractdate = "'- " + form.addsubtract_datevalue.value + " " + form.addsubtract_datetype.value + "'";
}

After that, we need to make changes in every echo statement in our Javascript code to handle this add/subtract feature.

if (sourceFormat == "timestamp" && destinationFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo $timestamp_value;`;
    } else {
        dateHtml = `echo strtotime(` + addsubtractdate + `, $timestamp_value);`;
    }
} else if (sourceFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo date('` + destinationFormat + `', $timestamp_value);`;
    } else {
        dateHtml = `echo date('` + destinationFormat + `', strtotime(` + addsubtractdate + `, $timestamp_value));`;
    }
} else if (destinationFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo strtotime($date_value);`;
    } else {
        dateHtml = `echo strtotime(` + addsubtractdate + `, strtotime($date_value));`;
    }
} else {
    if (addsubtractdate == "") {
        dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value));`;
    } else {
        dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value . ` + addsubtractdate + `));`;
    }
}

You can run the script now, and you will be able to generate the code for converting the date from one format to another. Moreover, you can also get the code for adding/subtracting days, months, or years from the resultant date. That’s how you can convert date format from one to another.

Learn how to calculate the time passed since the date in PHP and Javascript.

Calculate time passed since date – Javascript, PHP

Feel free to download the source code below.

[wpdm_package id=’1183′]

Calculate difference between 2 dates – jQuery

Demo – Calculate difference between 2 dates

Convert time to different timezones

Calculating difference between 2 dates requires 2 calendars to pick dates or you may want to calculate difference based on some database values. For example, say you have a project management site and when you create a project you also set it’s deadline too. Now you may want to know how many days are remaining till deadline, you will something like this:

$remaining_days = $deadline – $today;

So we will be using 2 different methods to calculate difference. 1st is by creating two input fields for the user to select the dates and 2nd method is by calculating difference from database datetime value.

From datetime picker

Start off by downloading the datetimepicker from the link below, you can also find this too in the source files at the end of this page:

Download datetimepicker

Download this library and place 3 files in your project:

  1. jquery.js
  2. build/jquery.datetimepicker.min.css
  3. build/jquery.datetimepicker.full.js

After that, include these files in your project, make sure to include jquery.js first:

<link rel="stylesheet" href="jquery.datetimepicker.min.css" />
<script src="jquery.js"></script>
<script src="jquery.datetimepicker.full.js"></script>

Now, create 2 input fields to select the dates and a button to click and calculate the difference:

<input type="text" id="date1" />
<input type="text" id="date2" />

<button onclick="calculateDifference();">Calculate</button>

First, you have to initialize both input fields to show the calendar when clicked:

<script>
    $("#date1").datetimepicker({
        timepicker: false,
        format: "Y-m-d"
    });

    $("#date2").datetimepicker({
        timepicker: false,
        format: "Y-m-d"
    });
</script>

At this point, you will be able to select 2 dates from 2 input fields. Now you have to implement the calculateDifference() inside <script> tag to actually perform the difference:

function calculateDifference() {
    // Get both values from input field and convert them into Javascript Date object
    var date1 = new Date($("#date1").val());
    var date2 = new Date($("#date2").val());

    // Difference can be calculated by subtracting the first date timestamp from second date timestamp
    var timeDifference = date2.getTime() - date1.getTime();

    // Just for debugging purpose
    console.log(timeDifference);
}

At this point, when you click the button, you will be able to see the difference in timestamp in your browser console. You can open the browser console by right clicking in empty area and select “Inspect element”. The 2nd tab should be named “Console”.

Now you have to convert this timestamp in days. As the timestamp is in milliseconds, you first have to convert them in seconds, then in hours, then finally in days.

// There are 1000 milliseconds in 1 second
var milliSecondsInOneSecond = 1000;

// There are 3600 seconds in 1 hour
var secondsInOneHour = 3600;

// And we all know there are 24 hours in 1 day
var hoursInOneDay = 24;

We have to divide this timestamp by the product of these 3 variables:

var days = timeDifference / (milliSecondsInOneSecond * secondsInOneHour * hoursInOneDay);
console.log(days);

If you check your browser console now, you will be able to view the difference of your 2 selected dates in days.

From database MySQL value

We are using a sample database called classicmodels, it will be included in the source files at the end of this page. We have a table called orders and 2 columns requiredDate and shippedDate. Subtracting shipped date from required date to know how many days it will take to send the product.

$days = $requiredDate – $shippedDate;

First we have to connect with database and get the record:

<?php
    $connection = mysqli_connect("localhost", "root", "", "classicmodels");
    $sql = "SELECT * FROM orders WHERE orderNumber = '10100'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_object($result);
?>

Now you have to convert these 2 datetime values in timestamp by using the PHP built-in function strtotime(). Then you can apply the same formula as above to convert milliseconds to days.

// Converting both values in timestamp milliseconds
$date1 = strtotime($row->shippedDate);
$date2 = strtotime($row->requiredDate);

// Calculating the difference in milliseconds
$date_difference = $date2 - $date1;

// Converting milliseconds into days
$days = round($date_difference / (60 * 60 * 24));
echo $days;

[wpdm_package id=’122′]