Friday, April 2, 2021

PHP cURL Examples

cURL is software which you can use to make various requests using different protocols. PHP has the option to use cURL and in this article, we’ll show several examples.

PHP cURL Basics

curl_init();      // initializes a cURL session
curl_setopt();    // changes the cURL session behavior with options
curl_exec();      // executes the started cURL session
curl_close();     // closes the cURL session and deletes the variable made by curl_init();

PHP cURL POST Request

A POST request is usually made to send user collected data to a server. 

<?php

$postRequest = array(
    'firstFieldData' => 'foo',
    'secondFieldData' => 'bar'
);

$cURLConnection = curl_init('http://hostname.tld/api');
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postRequest);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);

// $apiResponse - available data from the API request
$jsonArrayResponse - json_decode($apiResponse);

PHP cURL GET Request

A GET request retrieves data from a server. This can be a website’s HTML, an API response or other resources.

<?php

$cURLConnection = curl_init();

curl_setopt($cURLConnection, CURLOPT_URL, 'https://hostname.tld/phone-list');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

$phoneList = curl_exec($cURLConnection);
curl_close($cURLConnection);

$jsonArrayResponse - json_decode($phoneList);

PHP cURL Header

You can also set custom headers in your cURL requests. For this, we’ll use the curl_setopt() function.

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Header-Key: Header-Value',
    'Header-Key-2: Header-Value-2'
));
Source: https://www.webhostface.com/kb/knowledgebase/php-curl-examples/

Thursday, March 25, 2021

dayofweek() : Records of the weekdays

 

dayofweek() : Records of the weekdays

To get the number of weekday ( from 1 to 7 ) we will use dayofweek function of MySQL.
DAYOFWEEK(date)
Example
SELECT DAYOFWEEK('2016-05-06')
Output is 6.
For a invalid date output will give NULL
1 = Sunday , 2 = Monday, 3 = Tuesday, 4 = Wednesday , 5 = Thursday, 6 = Friday, 7 = Saturday

This function dayofweek returns values 1 to 7 based on the weekday starting from Sunday as 1, Monday as 2 and �so on for others. So if today is Thursday then dayofweek function will return 5. So we need before three days record ( excluding today ) from today to get the records stating from Monday. So we will deduct 2 from the weekday figure. Here is the query to get the records of all weekdays of a week till today.

SELECT id,date,weekday, dayofweek(CURDATE()) as dayofweek 
FROM dt_weekday 
WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL (dayofweek(CURDATE())-2) DAY ) AND CURDATE( )

Above query will collect records starting from Monday and ending with today. For example if today is Tuesday then you will get two records ( of Monday and Tuesday )

Please read the tutorial on last x day's record in part 1 of this tutorial. Here we will develop a query to get records of weekdays of the present week.

For your understanding we have displayed dayofweek value against each record.

Using weekday function

By using weekday function we will get the same result but here weekday will return different number for days.

Monday = 0, Tuesday = 1  and so on�� 

Here is a simple query

SELECT WEEKDAY(  '2014-08-15' )

Output of above query is 4 . (15th Aug 2014 is Friday).

Here is the query using weekday function to get records of the week starting from Monday.

SELECT id, DATE, weekday, WEEKDAY( CURDATE( ) ) AS weekday 
FROM dt_weekday 
WHERE  `date` BETWEEN DATE_SUB( CURDATE( ) , INTERVAL( WEEKDAY( CURDATE( ) ) ) DAY ) AND CURDATE( )

Previous One week records

By adjusting the interval in our above query we can return the records of previous Week starting from Monday to Saturday.

SELECT id, DATE, weekday, DAYOFWEEK( CURDATE( ) ) AS dayofweek 
FROM dt_weekday 
WHERE `date` 
BETWEEN DATE_SUB( CURDATE( ) , INTERVAL (dayofweek(CURDATE())+5) 
DAY ) 
AND DATE_SUB( CURDATE( ) , INTERVAL (dayofweek(CURDATE())) 
DAY ) 

Previous Two week records

This query can be further adjusted to return previous two weeks record. ( Check the difference with previous query )

SELECT id, DATE, weekday, DAYOFWEEK( CURDATE( ) ) AS dayofweek
FROM dt_weekday
WHERE  `date` 
BETWEEN DATE_SUB( CURDATE( ) , INTERVAL( DAYOFWEEK( CURDATE( ) ) +12 ) 
DAY ) 
AND DATE_SUB( CURDATE( ) , INTERVAL( DAYOFWEEK( CURDATE( ) ) +7 ) 
DAY )

Dynamic SQL Dump

Here is the sql dump to create table dt_weekday. This dump is dynamically created by considering previous 15 days and next 15 days starting from today. You will have one record for each day.

You should always take a fresh dump file from here for your testing, if you are not executing on same day.

One column weekday is kept to store name of the weekday ( sun, mon, tue � ) for your understanding.

CREATE TABLE IF NOT EXISTS `dt_weekday` (
`id` varchar(3) NOT NULL,
`date` date NOT NULL,
`weekday` varchar(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `dt_weekday` VALUES ('-15', '2021-04-09','Fri' );
INSERT INTO `dt_weekday` VALUES ('-14', '2021-04-08','Thu' );
INSERT INTO `dt_weekday` VALUES ('-13', '2021-04-07','Wed' );
INSERT INTO `dt_weekday` VALUES ('-12', '2021-04-06','Tue' );
INSERT INTO `dt_weekday` VALUES ('-11', '2021-04-05','Mon' );
INSERT INTO `dt_weekday` VALUES ('-10', '2021-04-04','Sun' );
INSERT INTO `dt_weekday` VALUES ('-9', '2021-04-03','Sat' );
INSERT INTO `dt_weekday` VALUES ('-8', '2021-04-02','Fri' );
INSERT INTO `dt_weekday` VALUES ('-7', '2021-04-01','Thu' );
INSERT INTO `dt_weekday` VALUES ('-6', '2021-03-31','Wed' );
INSERT INTO `dt_weekday` VALUES ('-5', '2021-03-30','Tue' );
INSERT INTO `dt_weekday` VALUES ('-4', '2021-03-29','Mon' );
INSERT INTO `dt_weekday` VALUES ('-3', '2021-03-28','Sun' );
INSERT INTO `dt_weekday` VALUES ('-2', '2021-03-27','Sat' );
INSERT INTO `dt_weekday` VALUES ('-1', '2021-03-26','Fri' );
INSERT INTO `dt_weekday` VALUES ('0', '2021-03-25','Thu' );
INSERT INTO `dt_weekday` VALUES ('1', '2021-03-24','Wed' );
INSERT INTO `dt_weekday` VALUES ('2', '2021-03-23','Tue' );
INSERT INTO `dt_weekday` VALUES ('3', '2021-03-22','Mon' );
INSERT INTO `dt_weekday` VALUES ('4', '2021-03-21','Sun' );
INSERT INTO `dt_weekday` VALUES ('5', '2021-03-20','Sat' );
INSERT INTO `dt_weekday` VALUES ('6', '2021-03-19','Fri' );
INSERT INTO `dt_weekday` VALUES ('7', '2021-03-18','Thu' );
INSERT INTO `dt_weekday` VALUES ('8', '2021-03-17','Wed' );
INSERT INTO `dt_weekday` VALUES ('9', '2021-03-16','Tue' );
INSERT INTO `dt_weekday` VALUES ('10', '2021-03-15','Mon' );
INSERT INTO `dt_weekday` VALUES ('11', '2021-03-14','Sun' );
INSERT INTO `dt_weekday` VALUES ('12', '2021-03-13','Sat' );
INSERT INTO `dt_weekday` VALUES ('13', '2021-03-12','Fri' );
INSERT INTO `dt_weekday` VALUES ('14', '2021-03-11','Thu' );
INSERT INTO `dt_weekday` VALUES ('15', '2021-03-10','Wed' );
INSERT INTO `dt_weekday` VALUES ('16', '2021-03-09','Tue' );

Source & Credit: https://www.plus2net.com/sql_tutorial/date-dayofweek.php

Getting the recent week, one month or year records from MySQL table

 

DATE_SUB() Getting the recent one month or year records from MySQL table

Syntax of DATE_SUB()
DATE_SUB(date, INTERVAL, expression, UNIT)
Example
SELECT DATE_SUB(  '2016-12-25', INTERVAL 3 DAY )
Output is 2016-12-22

We have subtracted three days form the given date by using DATE_SUB() function. In place of DAY we can use Month, year, hour, minute, second etc , here is the list.
unit ValueExpected expr FormatExample
DAYDAYSDATE_SUB( '2016-11-29', INTERVAL 10 DAY )
MONTHMONTHSDATE_SUB( '2015-11-20', INTERVAL 5 MONTH )
WEEKWEEKSDATE_SUB( '2016-08-20', INTERVAL 5 WEEK )
QUARTERQUARTERSDATE_SUB( '2016-08-20', INTERVAL 2 QUARTER )
YEARYEARSDATE_SUB( '2016-02-23', INTERVAL 2 YEAR )
YEAR_MONTH'YEARS-MONTHS'DATE_SUB( '2016-02-23', INTERVAL '2-5' YEAR_MONTH )
To use the above Examples add SELECT at left and run the query.
SELECT DATE_SUB( '2016-02-23', INTERVAL 2 YEAR ); // 2014-02-23 
SELECT DATE_SUB( CURDATE(), INTERVAL 2 YEAR ); // 2018-02-23
The second query depends on the todays date, so your result will be different.
Some time we have to collect last 7 or 15 days or X days (or month, year or week) data from MySQL table.

For example let us find out who are the new members joined in our forum in last week. One shop may be interested in knowing new products added in last one month. What are the books arrived in last one year. Here irrespective of the date values we want the records of last X days from today, or we can say that the records between today and last X days ( month , year or week) are required.

We will use the MySQL function CURDATE() to get the today's date.

To get the difference in today date and previous day or month we have to use the MySQL function DATE_SUB

DATE_SUB is a MySQL function which takes date expression, the interval and the constant to return the date value for further calculation.

Here are some sample queries on how to get the records as per requirements . �

Last 10 days records

select * from dt_table where  `date` >= DATE_SUB(CURDATE(), INTERVAL 10 DAY)
The above query will return last 10 days records. Note that this query will return all future dates also. To exclude future dates we have to modify the above command a little by using between query to get records. Here is the modified one.
SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 10 DAY ) AND CURDATE( )

Present Month Records

Starting from 1st day of the current month till now.
SELECT * FROM `dt_table` WHERE  date between  DATE_FORMAT(CURDATE() ,'%Y-%m-01') AND CURDATE()

Present Year Records

Starting from 1st Jan of the current Year till now.
SELECT * FROM `dt_table` WHERE  date between  DATE_FORMAT(CURDATE() ,'%Y-01-01') AND CURDATE()

Last one month records

Let us try to get records added in last one month
SELECT * FROM dt_table where  `date` >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
Here also future records will be returned so we can take care of that by using BETWEEN commands if required.
SELECT * FROM dt_table WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH)  AND CURDATE();
Using Year
select * from dt_table WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
Using year with BETWEEN
SELECT * FROM dt_table WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR)  AND CURDATE();

Records of previous month of any year

SELECT * FROM  dt_table WHERE MONTH( DATE ) = MONTH( DATE_SUB(CURDATE(),INTERVAL 1 MONTH ))

Records of previous month of same year

SELECT * FROM  dt_table WHERE MONTH( DATE ) = MONTH( DATE_SUB(CURDATE(),INTERVAL 1 MONTH )) 
AND 
YEAR( DATE ) = YEAR( DATE_SUB(CURDATE( ),INTERVAL 1 MONTH ))
Note the difference between Last one month record and Previous month record

Records of two date ranges

We can collect records between a particular date ranges by using between command and DATE_SUB. Here are some queries to generate records between two date ranges.
SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 3 MONTH ) AND DATE_SUB( CURDATE( ) ,INTERVAL 0 MONTH )
This query will return records between last three months. This query again we will modify to get the records between three moths and six months.
SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 6 MONTH ) AND DATE_SUB( CURDATE( ) ,INTERVAL 3 MONTH )
Now let us change this to get records between 6 month and 12 month.
SELECT * FROM dt_table WHERE `date` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 12  MONTH ) AND DATE_SUB( CURDATE( ) ,INTERVAL 6 MONTH )
With this you can understand how the records between a month range or a year range can be collected from a table. Note that the months ranges are calculated starting from current day. So if we are collecting records of last three months and we are in 15th day of 9th month then records of 15th day of 6th month we will get but the records of 14th day of 6th month will be returning on next query that is between 3 months and 6 months.

Records of present week

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())

Records of previous week

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())-1

Records of next week

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE())+1

Records of present week all working days ( Mon - Fri )

SELECT * FROM `dt_table` WHERE WEEKOFYEAR(date)=WEEKOFYEAR(CURDATE()) 
AND 
WEEKDAY(date)  BETWEEN 1 AND 5

Records of present week all working days till today

SELECT * FROM `dt_table` 
WHERE WEEKOFYEAR( DATE ) = WEEKOFYEAR( CURDATE( ) )
AND WEEKDAY( DATE ) BETWEEN 1 AND WEEKDAY(CURDATE())

Using Date and time Queries

Now let us calculate with Time

unit ValueExpected expr Format
Example
MICROSECONDMICROSECONDS
DATE_SUB( '2016-02-23 20:55:58', INTERVAL 225 MICROSECOND )
SECONDSECONDS
DATE_SUB( '2016-02-23 20:55:58', INTERVAL 2 SECOND )
MINUTEMINUTES
DATE_SUB( '2016-02-23 20:55:58', INTERVAL 2 MINUTE )
HOURHOURS
DATE_SUB( '2016-02-23 20:55:58', INTERVAL 5 HOUR )
SECOND_MICROSECOND'SECONDS.
MICROSECONDS'
DATE_SUB( '2016-02-23 20:55:58', INTERVAL '1.543' SECOND_MICROSECOND )
MINUTE_MICROSECOND'MINUTES:
SECONDS.
MICROSECONDS'
DATE_SUB
( '2016-02-23 20:55:58',
INTERVAL '5:2.743' MINUTE_MICROSECOND )
MINUTE_SECOND'MINUTES:
SECONDS'
DATE_SUB( '2016-02-23 20:55:58', INTERVAL '5:2' MINUTE_SECOND )
HOUR_MICROSECOND'HOURS:MINUTES:
SECONDS.
MICROSECONDS'
DATE_SUB( '2016-02-23 20:55:58', INTERVAL '5:2:1.249' HOUR_MICROSECOND)
HOUR_SECOND'HOURS:MINUTES:
SECONDS'
DATE_SUB( '2016-02-23 20:55:58', INTERVAL '5:2:1' HOUR_SECOND )
HOUR_MINUTE'HOURS:MINUTES'
DATE_SUB( '2016-02-23 20:55:52', INTERVAL '5:2' HOUR_MINUTE )
DAY_MICROSECOND'DAYS HOURS:
MINUTES:
SECONDS.
MICROSECONDS'
DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5:2:24.879' DAY_MICROSECOND
DAY_SECOND'DAYS HOURS:
MINUTES:SECONDS'
DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5:2:24' DAY_SECOND)
DAY_MINUTE'DAYS HOURS:
MINUTES'
DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5:2' DAY_MINUTE)
DAY_HOUR'DAYS HOURS'
DATE_SUB( '2016-02-23 20:55:52', INTERVAL '2 5' DAY_HOUR)

Our sample table dt_table_tm stores login date with time in a field along with one more column showing event_id.

All records of Last 5 Hours

SELECT * FROM `dt_table_tm` WHERE tm>=DATE_SUB(NOW(), INTERVAL 5 HOUR)

All records of Last 48 Hours

SELECT * FROM `dt_table_tm` WHERE tm>=DATE_SUB(NOW(), INTERVAL 48 HOUR)

All records of 15 hours 12 minutes

SELECT * FROM `dt_table_tm` WHERE tm>=DATE_SUB(NOW() , INTERVAL '15:12' HOUR_MINUTE)

In place of NOW() we can use specific date and time ( timestamp ) Note : While using date use the format YYYY-mm-dd ( YEAR - Month - date) and while using time use HH:MM:SS ( Hour : Minutes : Seconds )

SELECT * FROM  `dt_table_tm` WHERE tm >= DATE_SUB( '2018-08-10 11:50:00', INTERVAL '2:18:33' HOUR_SECOND )

All logins between 9 and 10 hours ( from 9 and 10 both inclusive till it is not 11 )

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 9 and 10

All logins betwee 9 and 10 for a perticular month and year

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 9 and 10 and MONTH(tm)=08 and year(tm)=2018

By Using date_format()

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 9 and 10 and date_format(tm,'%Y-%m')='2018-08'

All logins between 11 and 18 hours on a prticular day

SELECT * FROM `dt_table_tm` WHERE HOUR(tm) between 11 and 18 and date(tm)='2018-08-09'

All logins between two input times in hour : minutes : seconds on a perticular day

SELECT * FROM `dt_table_tm` WHERE date(tm)='2018-08-09' AND  TIME(tm) BETWEEN TIME('9:00:00') AND TIME('10:15:00')

Counting logins at different hours in all days ( using GROUP BY )

SELECT hour(tm) , count(event_id)   FROM `dt_table_tm` group by HOUR(tm)

First Login ( tm ) of all days. We will use GROUP BY and MIN()

SELECT DATE(tm), MIN(tm),DATE_FORMAT(MIN(tm),'%H : %i :%s') time 
FROM `dt_table_tm` GROUP BY  DATE(tm) 

First Login of all days after a particular hour. ( HOUR(tm) >16 )

SELECT DATE(tm), MIN(tm),DATE_FORMAT(MIN(tm),'%H : %i :%s') time
 FROM `dt_table_tm`  WHERE HOUR(tm) > 16 GROUP BY  DATE(tm)  

First login of all days after a particular HOUR Minutes and seconds.

SELECT DATE(tm), MIN(tm),DATE_FORMAT(MIN(tm),'%H : %i :%s') time 
 FROM `dt_table_tm`  WHERE TIME(tm) > '16:01:00'  GROUP BY  DATE(tm) 

Credit & Source: https://www.plus2net.com/sql_tutorial/date-lastweek.php

Sunday, February 21, 2021

How to Quickly Insert Date and Timestamp in Excel

A timestamp is something you use when you want to track activities.

For example, you may want to track activities such as when was a particular expense incurred, what time did the sale invoice was created, when was the data entry done in a cell, when was the report last updated, etc.

Let’s get started.

Keyboard Shortcut to Insert Date and Timestamp in Excel

If you have to insert the date and timestamp in a few cells in Excel, doing it manually could be faster and more efficient.

Here is the keyboard shortcut to quickly enter the current Date in Excel:

Control + : (hold the control key and press the colon key).

Here is how to use it:

  • Select the cell where you want to insert the timestamp.
  • Use the keyboard shortcut Control + :
    • This would instantly insert the current date in the cell.

Automatically insert Timestamp in Excel - Keyboard shortcut

A couple of important things to know:

  • This shortcut would only insert the current date and not the time.
  • It comes in handy when you want to selectively enter the current date.
  • It picks the current date from your system’s clock.
  • Once you have the date in the cell, you can apply any date format to it. Simply go to the ‘Number Format’ drop-down in the ribbon and select the date format you want.

Note that this is not dynamic, which means that it will not refresh and change the next time you open the workbook. Once inserted, it remains as a static value in the cell.

While this shortcut does not insert the timestamp, you can use the following shortcut to do this:

Control + Shift + :

This would instantly insert the current time in the cell.

Automatically insert date and Timestamp in Excel - shift-control-colon

So if you want to have both date and timestamp, you can use two different cells, one for date and one for the timestamp.

Using TODAY and NOW Functions to Insert Date and Timestamps in Excel

In the above method using shortcuts, the date and timestamp inserted are static values and don’t update with the change in date and time.

If you want to update the current date and time every time a change is done in the workbook, you need to use Excel functions.

This could be the case when you have a report and you want the printed copy to reflect the last update time.

Insert Current Date Using TODAY Function

To insert the current date, simply enter =TODAY() in the cell where you want it.

Automatically insert Timestamp in Excel - Using Today Function

Since all the dates and times are stored as numbers in Excel, make sure that the cell is formatted to display the result of the TODAY function in the date format.

To do this:

  • Right-click on the cell and select ‘Format cells’.Automatically insert Timestamp in Excel - format cells
  • In the Format Cells dialog box, select Date category in the Number tab.Automatically insert Timestamp in Excel - date-category
  • Select the required date format (or you can simply go with the default one).
  • Click OK.

Note that this formula is volatile and would recalculate every time there is a change in the workbook.

Insert Date and Timestamp Using NOW Function

If you want the date and timestamp together in a cell, you can use the NOW function.

Automatically insert date and Timestamp in Excel - now function

Again, since all the dates and times are stored as numbers in Excel, it is important to make sure that the cell is formatted to have the result of the NOW function displayed in the format that shows the date as well as time.

To do this:

  • Right-click on the cell and select ‘Format cells’.
  • In the Format Cells dialog box, select ‘Custom’ category in the Number tab.
  • In the Type field, enter dd-mm-yyyy hh:mm:ssinsert-date-and-timestamp-in-excel-custom-format
  • Click OK.

This would ensure that the result shows the date as well as the time.

Note that this formula is volatile and would recalculate every time there is a change in the workbook.

Circular References Trick to Automatically Insert Date and Timestamp in Excel

One of my readers Jim Meyer reached out to me with the below query.

“Is there a way we can automatically Insert Date and Time Stamp in Excel when a data entry is made, such that it does not change every time there is a change or the workbook is saved and opened?”

This can be done using the keyboard shortcuts (as shown above in the tutorial). However, it is not automatic. With shortcuts, you’ll have to manually insert the date and timestamp in Excel.

To automatically insert the timestamp, there is a smart technique using circular references (thanks to Chandoo for this wonderful technique).

Let’s first understand what a circular reference means in Excel.

Suppose you have a value 1 in cell A1 and 2 in cell A2.

Now if you use the formula =A1+A2+A3 in cell A3, it will lead to a circular reference error. You may also see a prompt as shown below:

circular reference prompt in Excel

This happens as you are using the cell reference A3 in the calculation that is happening in A3.

Now, when a circular reference error happens, there is a non-ending loop that starts and would have led to a stalled Excel program. But the smart folks in the Excel development team made sure that when a circular reference is found, it is not calculated and the non-ending loop disaster is averted.

However, there is a mechanism where we can force Excel to at least try for a given number of times before giving up.

Now let’s see how we can use this to automatically get a date and timestamp in Excel (as shown below).

inserting the date and time automatically using circular reference

Note that as soon as I enter something in cells in column A, a timestamp appears in the adjacent cell in column B. However, if I change a value anywhere else, nothing happens.

Here are the steps to get this done:

  • Go to File –> Options.insert-date-and-timestamp-in-excel-options
  • In the Excel Options dialog box, select Formulas.Changing formulas settings in Excel
  • In the Calculated options, check the Enable iterative calculation option.Enable iterative calculation in Excel for inserting timestamps
  • Go to cell B2 and enter the following formula:
    =IF(A2<>"",IF(B2<>"",B2,NOW()),"")

That’s it!

Now when you enter anything in column A, a timestamp would automatically appear in column B in the cell adjacent to it.

insert-date-and-timestamp-in-excel-timestamp-demo

With the above formula, once the timestamp is inserted, it doesn’t update when you change the contents of the adjacent cell.

If you want the timestamp to update every time the adjacent cell in Column A is updated, use the below formula (use Control + Shift + Enter instead of the Enter key):

=IF(A2<>"",IF(AND(B2<>"",CELL("address")=ADDRESS(ROW(A2),COLUMN(A2))),NOW(),IF(CELL("address")<>ADDRESS(ROW(A2),COLUMN(A2)),B2,NOW())),"")

insert-date-and-timestamp-in-excel-timestamp-update-demo

This formula uses the CELL function to get the reference of the last edited cell, and if it’s the same as the one to the left of it, it updates the timestamp.

Note: When you enable iterative calculations in the workbook once, it will be active until you turn it off. To turn it off, you need to go to Excel Options and uncheck the ‘Enable iterative calculation’ option.

Using VBA to Automatically Insert Timestamp in Excel

If VBA is your weapon of choice, you’ll find it to be a handy way to insert a timestamp in Excel.

VBA gives you a lot of flexibility in assigning conditions in which you want the timestamp to appear.

Below is a code that will insert a timestamp in column B whenever there is any entry/change in the cells in Column A.

'Code by Sumit Bansal from https://trumpexcel.com
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Handler
If Target.Column = 1 And Target.Value <> "" Then
Application.EnableEvents = False
Target.Offset(0, 1) = Format(Now(), "dd-mm-yyyy hh:mm:ss")
Application.EnableEvents = True
End If
Handler:
End Sub

This code uses the IF Then construct to check whether the cell that is being edited is in column A. If this is the case, then it inserts the timestamp in the adjacent cell in column B.

Note that this code would overwrite any existing contents of the cells in column B. If you want. You can modify the code to add a message box to show a prompt in case there is any existing content.

Where to Put this Code?

This code needs to be entered as the worksheet change event so that it gets triggered whenever there is a change.

To do this:

  • Right-click on the worksheet tab and select View Code (or use the keyboard shortcut Alt + F11 and then double click on the sheet name in the project explorer).insert-date-and-timestamp-in-excel-sheet-right-click
  • Copy-paste this code into the code window for the sheet.insert-date-and-timestamp-in-excel-worksheet-change-code2
  • Close the VB Editor.

Make sure you save the file with .XLS or .XLSM extension as it contains a macro.

Creating a Custom Function to Insert Timestamp

Creating a custom function is a really smart way of inserting a timestamp in Excel.

It combines the power of VBA with functions, and you can use it like any other worksheet function.

Here is the code that will create a custom “Timestamp” function in Excel:

'Code by Sumit Bansal from http://trumpexcel.com
Function Timestamp(Reference As Range)
If Reference.Value <> "" Then
Timestamp = Format(Now, "dd-mm-yyy hh:mm:ss")
Else
Timestamp = ""
End If
End Function

Where to Put this Code?

This code needs to be placed in a module in the VB Editor. Once you do that, the Timestamp function becomes available in the worksheet (just like any other regular function).

Here are the steps to place this code in a module:

  • Press ALT + F11 from your keyboard. It will open the VB Editor.
  • In the Project Explorer in VB Editor, right-click on any of the objects and go to Insert –> Module. This will insert a new module.insert-date-and-timestamp-in-excel-insert-module
  • Copy-paste the above code in the module code window.insert-date-and-timestamp-in-excel-code-in-module
  • Close the VB Editor or press ALT + F11 again to go back to the worksheet.

Now you can use the function in the worksheet. It will evaluate the cell to its left and insert the timestamp accordingly.

insert-date-and-timestamp-in-excel-timestamp-formula

It also updates the timestamp whenever the entry is updated.

Make sure you save the file with .XLS or .XLSM extension as it contains VB code.

Hope you’ve found this tutorial useful. 


Source & Credits: https://trumpexcel.com/date-timestamp-excel/

How to change the PHP version for subfolders or subdomains

  How to change the PHP version for subfolders or subdomains Setting a specific PHP version for a specific websites, subfolders or subdomain...