Showing posts with label PHP DATE. Show all posts
Showing posts with label PHP DATE. Show all posts

Friday, 2 August 2019

How to transform a month number to the relevant month name using PHP

This can be obtained by combining the date function with the mktime function
For example if I want to get Jan from the number 1 which represents the first monthin the year I would use something similar to the below
$i = 1; //The number 1 represents January
 
echo date("M",mktime(0,0,0,$i,1,2010)); //This will output Jan
So if you want to output Feb the value of $i would be 2 etc
USAGE:
date = string date ( string $format [, int $timestamp ] ) (PHP 4 & 5)
mktime = int mktime ([ int $hour = date(“H”) [, int $minute = date(“i”) [, int $second = date(“s”) [, int $month = date(“n”) [, int $day = date(“j”) [, int $year = date(“Y”) [, int $is_dst = -1 ]]]]]]] )  (PHP 4 & 5)

How to add months to a given date using PHP

By using the PHP functions date and strtotime this can be accomplished.
Example 
$date = '2010-03-22'; 
 
$new_date = date('Y-m-d',strtotime('+4 months',strtotime($date))); 
 
echo $new_date; //Displays 2010-07-22
Explanation of PHP functions:
1)
FUNCTION
date
DESCRIPTION
string
 date ( string $format [, int $timestamp ] )
PARAMETERS USED IN THIS EXAMPLE
Y = A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
= Numeric representation of a month, with leading zeros (01 through 12)
= Day of the month, 2 digits with leading zeros (01 to 31)
2)
FUNCTION
strtotime
DESCRIPTION
int strtotime ( string $time [, int $now ] )
PARAMETERS
time The string to parse. Before PHP 5.0.0, microseconds weren’t allowed in the time, since PHP 5.0.0 they are allowed but ignored.
now The timestamp which is used as a base for the calculation of relative dates.

Monday, 24 September 2018

How to Format Date for Display or Use In a Shell Script


How do I format date to display on screen on for my shell scripts as per my requirements on Linux or Unix like operating systemsYou need to use the standard date command to format date or time. You can use the same command with the shell script.
 The syntax is
  1. date +FORMAT 
  2. date +"%FORMAT"
  3. date +"%FORMAT%FORMAT" 
  4. date +"%FORMAT-%FORMAT"

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +"%m-%d-%y"Sample output:
02-27-07
To turn on 4 digit year display:
$ date +"%m-%d-%Y"Just display date as mm/dd/yy format:
$ date +"%D"

Task: Display time only

Type the following command:
$ date +"%T"Outputs:
19:55:04
To display locale's 12-hour clock time, enter:
$ date +"%r"Outputs:
07:56:05 PM
To display time in HH:MM format, type:
$ date +"%H-%M"Sample outputs:
00-50

How do I save time/date format to the shell variable?

$ NOW=$(date +"%m-%d-%Y"To display a variable use echo / printf command:
$ echo $NOW

A sample shell script

#!/bin/bash
NOW=$(date +"%m-%d-%Y")
FILE="backup.$NOW.tar.gz"
echo "Backing up data to /nas42/backup.$NOW.tar.gz file, please wait..."
# rest of script
# tar xcvf /nas42/backup.$NOW.tar.gz /home/ /etc/ /var
 

A complete list of FORMAT control characters supported by the date command

FORMAT controls the output. It can be the combination of any one of the following:
%FORMAT StringDescription
%%a literal %
%alocale's abbreviated weekday name (e.g., Sun)
%Alocale's full weekday name (e.g., Sunday)
%blocale's abbreviated month name (e.g., Jan)
%Blocale's full month name (e.g., January)
%clocale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%Ccentury; like %Y, except omit last two digits (e.g., 21)
%dday of month (e.g, 01)
%Ddate; same as %m/%d/%y
%eday of month, space padded; same as %_d
%Ffull date; same as %Y-%m-%d
%glast two digits of year of ISO week number (see %G)
%Gyear of ISO week number (see %V); normally useful only with %V
%hsame as %b
%Hhour (00..23)
%Ihour (01..12)
%jday of year (001..366)
%khour ( 0..23)
%lhour ( 1..12)
%mmonth (01..12)
%Mminute (00..59)
%na newline
%Nnanoseconds (000000000..999999999)
%plocale's equivalent of either AM or PM; blank if not known
%Plike %p, but lower case
%rlocale's 12-hour clock time (e.g., 11:11:04 PM)
%R24-hour hour and minute; same as %H:%M
%sseconds since 1970-01-01 00:00:00 UTC
%Ssecond (00..60)
%ta tab
%Ttime; same as %H:%M:%S
%uday of week (1..7); 1 is Monday
%Uweek number of year, with Sunday as first day of week (00..53)
%VISO week number, with Monday as first day of week (01..53)
%wday of week (0..6); 0 is Sunday
%Wweek number of year, with Monday as first day of week (00..53)
%xlocale's date representation (e.g., 12/31/99)
%Xlocale's time representation (e.g., 23:13:48)
%ylast two digits of year (00..99)
%Yyear
%z+hhmm numeric timezone (e.g., -0400)
%:z+hh:mm numeric timezone (e.g., -04:00)
%::z+hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::znumeric time zone with : to necessary precision (e.g., -04, +05:30)
%Zalphabetic time zone abbreviation (e.g., EDT)

Monday, 10 September 2018

PHP's getdate() function

I've been coding PHP since 1999 and I'm still discovering functions I didn't know about. Just the other day I read someone's post about some useful PHP functions and I knew all of them except for the getdate() function so I thought I'd cover it here.
PHP has the very useful date() function for formatting dates and times which I use frequently myself but often find myself doing something like this if I need both the year and the month:
$month = date('j'); // day of the month without leading zeroes
$year = date('Y'); // 4 digit year
That's not the most efficient way of doing things, especially if you need to get some other variables as well, because it's making multiple calls to the date() function. Enter the getdate() function.
Calling getdate() without parameters will use the current date and time and assign the various variables to an associative array like so:
$date = getdate();
print_r($date);
The above outputs this:
Array
(
    [seconds] => 55
    [minutes] => 41
    [hours] => 11
    [mday] => 19
    [wday] => 0
    [mon] => 4
    [year] => 2009
    [yday] => 108
    [weekday] => Sunday
    [month] => April
    [0] => 1240098115
)
You can also specify a timestamp if you had your date in that format already (or by converting it using the strtortime()function). The following example uses the timestamp for midnight on April 1st 2009:
$date = getdate(1238497200);
print_r($date);
And the output:
Array
(
    [seconds] => 0
    [minutes] => 0
    [hours] => 0
    [mday] => 1
    [wday] => 3
    [mon] => 4
    [year] => 2009
    [yday] => 90
    [weekday] => Wednesday
    [month] => April
    [0] => 1238497200
)
Going back to the example at the start of this post, I could now do this instead of calling date() multiple times:
$date = getdate();
... $date['mon'] ...;
... $date['year'] ...;

Related posts:

PHP Date Constants

When writing my "Get a list of all available constants with PHP" post I discovered there are a number of usful date format constants in PHP which can be used with the date() function. (Refer to my "Formatting Dates with PHP" post for more details about the PHP date function). This post looks at these constants and how to use them with the date function. Please note that these constants have only been present in PHP since 5.1.1.

Example usage

The following example will get the current date and time in the valid format for an RSS feed and assign it to the $date variable:
$date = date(DATE_RSS);

Date constants

The available date constants are listed below with offsite links to the appropriate RFC or ISO standard which define it, where applicable. Please note that these constants are available only from PHP version 5.1.1. The datetimes in the examples below are from the original post date of this article in New Zealand standard time.
DATE_ATOM
This is the format for Atom feeds. The PHP format is "Y-m-d\TH:i:sP" and example output from date(DATE_ATOM) is "2008-08-16T12:00:00+12:00"
DATE_COOKIE
This is the format for cookies set from a web server or Javascript. The PHP format is "l, d-M-y H:i:s T" and example output from date(DATE_COOKIE) is "Sat, 16 Aug 2008 12:00:00 NZST"
DATE_ISO8601
This is the format for ISO8601, an international date and time format standard. The PHP format is "Y-m-d\TH:i:sO" and example output from date(DATE_ISO8601) is "2008-08-16T12:00:00+1200". Read about ISO8601 at Wikipedia.
DATE_RFC822
This is the format for RFC822 which defines the standards for email messages. The PHP format is "D, d M y H:i:s O" and example output from date(DATE_RFC822) is "Sat, 16 Aug 2008 12:00:00 NZST". Read about RFC822 at faqs.org
DATE_RFC850
This is the format for RFC850 which defines the standards for USENET messages. The PHP format is "l, d-M-y H:i:s T" and example output from date(DATE_RFC850) is "Saturday, 16-Aug-08 12:00:00 NZST". Read about RFC850 at faqs.org
DATE_RFC1036
This is the format for RFC1036, a later definition for USENET. The PHP format is "l, d-M-y H:i:s T" (the same as for DATE_RFC850) and example output from date(DATE_RFC1036) is "Saturday, 16-Aug-08 12:00:00 NZST". Read about RFC1036 at faqs.org
DATE_RFC1123
This is the format for RFC1123 and covers requirements for Internet hosts. The PHP format is "D, d M Y H:i:s T" and example output from date(DATE_RFC1123) is "Sat, 16 Aug 2008 12:00:00 NZST" Read about RFC1123 at faqs.org
DATE_RFC2822
This is the format for RFC2822 which updates RFC822 for email messages. The PHP format is "D, d M Y H:i:s O" and example output from date(DATE_RFC2822) is "Sat, 16 Aug 2008 12:00:00 +1200" Read about RFC2822 at faqs.org
DATE_RFC3339
This is the format for RFC3339 and defines "date and time on the Internet". The PHP format is "Y-m-d\TH:i:sP" and example output from date(DATE_RFC3339) is "2008-08-16T12:00:00+12:00" Read about RFC3339 at faqs.org
DATE_RSS
This is the format for RSS feeds. The PHP format is "D, d M Y H:i:s T" and example output from date(DATE_RSS) is "Sat, 16 Aug 2008 12:00:00 NZST"
DATE_W3C
This is the format for "World Wide Web Consortium" according to the PHP documentation, although I'm not sure what this actually means. The PHP format is "Y-m-d\TH:i:sP" and example output from date(DATE_W3C) is "2008-08-16T12:00:00+12:00"

Related posts:

Get the number of days in a month with PHP

This post shows how to get the number of days in a month with PHP by specifying the year and month. This can be useful when generating a calendar application without having to manually code in the number of days each month has, and not having to worry about the number of days in February which varies on leap years.

cal_days_in_month() function

The PHP function cal_days_in_month() returns the number of days for a given month and year. Which calendar to use is also a parameter but it would be rare to use anything other than CAL_GREGORIAN.
The first example would echo the number of days in August 2009 (the month and year this post was written), which is 31:
echo cal_days_in_month(CAL_GREGORIAN, 8, 2009);
The second example loops through the years from 2000 to 2008 and echos the number of days in February for each of those years:
for($i = 2000; $i < 2009; $i++) {
    echo "$i: ", cal_days_in_month(CAL_GREGORIAN, 2, $i), "\n";
}
The output from the above example is:
2000: 29
2001: 28
2002: 28
2003: 28
2004: 29
2005: 28
2006: 28
2007: 28
2008: 29

Current Month: date("t")

To get the number of days for the current month you can simply use the date() function passing in "t" as the format. This returns the number of days for the given month, and when no timestamp is passed in is the current datetime.

Related posts:

Using strtotime with PHP

The strtotime() function in PHP allows you to convert English text date time strings into UNIX timestamps. It is useful for converting database datetime strings into UNIX timestamps and also creating dates into the future or past based on the current time or relative to a date and time in the future or the past. This post looks at some examples of doing this.
The PHP function strtotime() has the following usage:
int strtotime ( string $time [, int $now ] )
This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.
An example of this usage is as follows, where the date passed to strtotime() might be a date from a database query or similar:
$ts = strtotime('2007-12-21');
This will return into the $ts variable the value 1198148400, which is the UNIX timestamp for the date December 21st 2007. This can be confirmed using the date() function like so:
echo date('Y-m-d', 1198148400);
// echos 2007-12-21
strtotime() is able to parse a wide variety of strings and convert them to the appropriate timestamp, using actual dates and also strings such as "next week", "next tuesday", "last thursday", "2 weeks ago" and so on. Here are some examples:
$ts = strtotime('21 december 2007');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';
This will display the following:
1198148400
2007-12-21
If today is December 21st, then the following:
$ts = strtotime('next week');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('next tuesday');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('last thursday');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('2 weeks ago');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('+ 1 month');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';
will display the following:
1199006542
2007-12-30
1198494000
2007-12-25
1198062000
2007-12-20
1197192142
2007-12-09
1201080142
2008-01-23

Using strtotime to offset from a different date

If you want to use the PHP function strtotime to add or subtract a number of days, weeks, months or years from a date other than the current time, you can do it by passing the second optional parameter to the strtotime() function, or by adding it into the string which defines the time to parse.
This example shows passing the second parameter. Doing it this way requires that the date to offset from is already a UNIX timestamp. In this example the timestamp being passed is December 25th 2007 (Christmas Day).
$ts = strtotime('tomorrow', 1198494000);
echo $ts, '<br />';
echo date('Y-m-d', $ts);
The result would be:
1198580400
2007-12-26
As you can see, 'tomorrow' has been parsed as tomorrow starting from the 1198494000 timestamp, which is December 25th 2007, resulting in a timestamp being returned as December 26th 2007.
Another way to add or subtract time from an existing time string is to add it into the datetime string like so, where we are adding 90 days on to a date value, in the format of the MySQL date field:
$ts = strtotime('2007-10-12 +90 days');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';
This would output:
1199876400
2008-01-10
As you can see the strtotime() function is extremely useful for parsing English (and databases) representations of date and time strings and turning them into UNIX timestamps. It is also useful for adding plus and minus offsets to those timestamps to easily create dates and times in the future and past.

Related posts:

Monday, 20 July 2015

PHP: Expiry date code

<?php
    date_default_timezone_set ("Asia/Calcutta");
    $dateofreg1=date("M d Y");
    $puechese_date="08/13/2014";
    $startTime = strtotime($puechese_date);
    $endTime = strtotime($dateofreg1);
    $timeDiff = abs($startTime-$endTime);
    $numberDays = $timeDiff/86400;
    $numberDays = intval($numberDays);
    $validays="90";
    if($numberDays>$validays)
        {
        echo "Product Valid";
        }
    else
        {
        echo "Product Expired";
        }
?>

Monday, 13 July 2015

PHP: Function to get the last day of a month

<?php
/**
    Last date of a month of a year
    
    @param[in] $month - Integer. Default = Current Month
    @param[in] $year - Integer. Default = Current Year
    
    @return Last date of the month and year in yyyy-mm-dd format
*/
function last_day($month = '', $year = '')
{
   if (empty($month))
   {
      $month = date('m');
   }
   
   if (empty($year))
   {
      $year = date('Y');
   }
   
   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));

   return date('Y-m-d', $result);
}
?>

Saturday, 27 June 2015

Mysql: How convert mysql date in php, back and foward

Dates in PHP and MySQL

I see a lot of people on forums and on my training courses asking about the
best way (or any way) to manage dates stored in a MySQL database and used in PHP.
Three options follow, but first the problem. PHP uses unix timestamps for all its date functionality.
It has methods to convert these timestamps into pretty much any text format you
could want but internally it uses the timestamp format. A timestamp is simply an integer.
Specifically, it's the number of seconds that have elapsed since
midnight on January 1st 1970 (greenwich mean time).
MySQL has three date types for use in columns. These are DATETIME, DATE, and TIMESTAMP.
DATETIME columns store date and time in some internal format (I've not found what that is)
for efficiency but always converts them to/from a string in the form YYYY-MM-DD HH:MM:SS
(e.g. 2006-12-25 13:43:15) when accessing them. DATE columns use just the date part of
this format - YYYY-MM-DD (e.g. 2006-12-25). TIMESTAMP columns, despite their name, are
nothing like the unix timestamps used in PHP. A TIMESTAMP column is simply a DATETIME column
that automatically updates to the current time every time the contents of that record are
altered. (That's a simplification but broadly true and the details are not important here).
In particular, since version 4.1 of MySQL the TIMESTAMP format is exactly the same as the
DATETIME format.

So the problem is how to work with these two very different date formats -
the PHP timestamp integer and the MySQL DATETIME string. There are three common
solutions...
  1. One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -
    $mysqldate = date( 'Y-m-d H:i:s', $phpdate ); $phpdate = strtotime( $mysqldate );
  2. Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -
    $query = "UPDATE table SET
        datetimefield = FROM_UNIXTIME($phpdate)
        WHERE...";
    $query = "SELECT UNIX_TIMESTAMP(datetimefield)
        FROM table WHERE...";
  3. Our last option is simply to use the PHP timestamp format everywhere. Since a PHP timestamp is a signed integer, use an integer field in MySQL to store the timestamp in. This way there's no conversion and we can just move PHP timestamps into and out of the database without any issues at all.
    Be aware, however, that by using an integer field to store your dates you lose a lot of functionality within MySQL because MySQL doesn't know that your dates are dates. You can still sort records on your date fields since php timestamps increase regularly over time, but if you want to use any of MySQL's date and time functions on the data then you'll need to use FROM_UNIXTIME to get a MySQL DATETIME for the function to work on.
    However, if you're just using the database to store the date information and any manipulation of it will take place in PHP then there's no problems.

So finally we come to the choice of which to use. For me, if you don't need to manipulate the dates within MySQL then there's no contest and the last option is the best. It's simple to use and is the most efficient in terms of storage space in the data table and speed of execution when reading and writing the data.

However, some queries will be more complicated because your date is not in a date field (e.g. select all users who's birthday is today) and you may lose out in the long run. If this is the case it may be better to use either option 1 or 2. Which of these you use depends on whether you'd rather place the work on MySQL or PHP. I tend to use option 2 but there's no right or wrong answer - take your pick.

Friday, 19 June 2015

PHP: Date function to display all dates between two dates

There is the DatePeriod class.
EXAMPLE:
$begin = new DateTime('2013-02-01');
$end = new DateTime('2013-02-13');

$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);

foreach($daterange as $date){
    echo $date->format("Y-m-d") . "<br>";
}
(P1D stands for period of one day, see DateInterval for further documentation)
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
table,th,td{
    border:1px solid black;
}
th,td{
    height:40px;
    width:140px;
    font-weight:bold;
}
</style>
</head>

<body>
<?php
$start_date = date('Y-m-d',time()-84600);
//echo date('d/m/Y', strtotime('+2 months'));
//echo date('M d Y',$date);
$end_date = date('Y-m-d',strtotime('+3 months'));
//echo date('d/m/Y', strtotime('+1 day'));

//echo strtotime('+1 day');
$begin = new DateTime($start_date);
$end = new DateTime($end_date);

$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);


?>
<table cellpadding="0" cellspacing="0" width="100%">
    <thead>
        <tr>
                <th>#</th>
                <td>Date</td>
                <td>SM</td>
                <td>Auditing</td>
                <td>Accounts</td>
                <td>IT</td>
        </tr>
    </thead>
    <tbody>
    <?php
    $i=1;
    foreach($daterange as $date){ ?>
        <tr>
            <td rowspan="2"><?php  echo $i; ?></td>
            <td rowspan="2"><?php  echo $date->format("M d Y"); ?></td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
        </tr>
        <tr>
            <td>test</td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
        </tr>
       
        <?php $i++; } ?>
    </tbody>
</table>
</body>
</html>


Another way:
<?php 
  $day = 86400; // Day in seconds  
        $format = 'Y-m-d'; // Output format (see PHP date funciton)  
        $sTime = strtotime($start_date); // Start as time  
        $eTime = strtotime($end_date); // End as time  
        $numDays = round(($eTime - $sTime) / $day) + 1;  
        $days = array();  

        for ($d = 0; $d < $numDays; $d++) {  
            $days[] = date($format, ($sTime + ($d * $day)));  
        }  
 ?>