Home > Articles

  • Print
  • + Share This

Loading Today's Date into an Array

Problem

You want to load today's date and time into an array for further manipulation.

Solution

Use PHP's getdate() function, which returns an associative array of seconds, minutes, hours, mday (day of the month), wday (day of the week), mon (current month number), year (number), yday (day of the year as a number), weekday (day of the week in text form), and month (month of the year in text form):

<?php
$date_ar = getdate();
?>

Discussion

This is very useful in many ways. It enables us to do things such as format the current date in MM/DD/YYYY format:

<?php
$da = getdate();
$datestamp = "$da[mday]/$da[mon]/$da[year]";
?>

In this case, you can also use the date() function, which returns a formatted string according to the arguments that you provide:

<?php
$datestamp = date ("j/n/Y");
?>

If you are looking for C/Perl compatibility, you can use PHP's localtime() function, which returns a numerically indexed array with the current time or an associative array with the current time. The indexes have the same names as the corresponding C structure elements.

<?php

$date1 = localtime();
$date2 = localtime (time(), 1);

print "$date1[5] is the same as $date2[tm_year]";
?>
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.