Friday, 3 June 2016

CONVERT LIST OF DATES TO TIMESTRING WITH PHP

Working with dates is a hugely common feature of systems. The problem as humans is we don’t have a universally agreed upon format. The UK will use dd/mm/yyyy, America uses mm/dd/yyyy and even combinations of these.
Luckily with computer systems we have a generally agreed upon timeformat called a UNIX timestamp, sometimes referred to as a Epoch timestamp or Posix time.
This timestamp is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.
For this reason you may sometimes have a list of dates you want to convert to the EPOCH timestamp. This is fairly easy with online tools if you only have 1 timestamp to do. However when you have hundreds to convert (imagine migrating from one system to another and wanting to change the way you store dates in your database).
The below PHP code/snippet will help you easily generate a list of timestamps for the dates you feed into it.
<?php
// Create the function to accept the date format you're expecting. In this case it's dd/mm/yyyy, you can just swap the j/n/y around if you want to accept different combinations.
function dateToTimestamp($date) {
  return DateTime::createFromFormat('j/n/Y', $date)->getTimestamp();
}

// Example dates, list your own here in the array:
$dates=[
'18/6/2015',
'25/9/2015',
'19/6/2015',
'3/7/2015',
'25/6/2015',
'10/7/2015'
];

// This foreach will loop over all the dates you provided and print out the EPOCH timestamp version.
foreach ($dates as $date) {
  echo dateToTimestamp($date);
  echo '<br>';
}
?>

0 comments:

Post a Comment