Arvind
Arvind

Reputation: 21

php date output in yy instead of yyyy

I have very little knowledge of PHP.

I am trying to display or pass the 1st day of month in dd/mm/yyyy format but the result is dd/mm/yy.

My PHP query is

<? php
$month='Aug'
$year='2015'

$c=pdgwoconnect(); 
$sqlmy="SELECT TO_DATE("$month/$year","MM/YYYY")FRMDT, TO_DATE("$nextm/$year","MM/YYYY")TODT FROM DUAL";
$resultmy = OCIParse($c, $sqlmy);
OCIExecute($resultmy);

while ($row = oci_fetch_array($resultmy, OCI_ASSOC)) {
    $frmdt= $row["FRMDT"];
    $todt= $row["TODT"];
    echo $frmdt;
    echo "</br>";
    echo $todt;
}
?>

Result is 01-AUG-15 and 01-SEP-15

I want this in format 01-08-2015 or 01-AUG-2015 like this.

Upvotes: 2

Views: 1115

Answers (3)

Kleskowy
Kleskowy

Reputation: 2668

First of all: Why would you need to select a date from DB?

The timezone set on your database engine / database connection can be different than the one you want, and it consumes resources (time mostly). So using DB for getting just the date and time seems to be unnecessary, unadvised an also unefficient.

Unless you have a very strict reason for that, I would recommend using PHP to retrieve the date you need, and here's how you can do it:

<?php
   // your input data as posted
   $month='Aug';
   $year='2015';
   $day = '01'; // since you need a first day of the month

   //create proper timezone that you need - I chose "Europe/London"
   $timeZoneString = 'Europe/London';
   $timeZone = new DateTimeZone($timeZoneString);

   //date string has to match format given in DateTime::createFromFormat()
   $dateString = "{$year}-{$month}-{$day}";
   $dateTime = DateTime::createFromFormat('Y-M-d', $dateString, $timeZone);

   //you could see here what DateTime object looks like
   //var_dump($dateTime);

   //print the current date - the 1st Aug 2015 in deisred format
   echo $dateTime->format("d/m/Y"); // prints "01/08/2015"

   //create proper datetime interval
   $dateIntervalString = 'P1M'; // +1 month
   $dateInterval = new DateInterval($dateIntervalString);

   //add datetime interval to your date
   $dateTime->add($dateInterval);

   //print the date as you like, e.g. "dd/mm/yyyy"
   echo $dateTime->format("d/m/Y"); // prints "01/09/2015"

I checked this code and it works, and it has following advantages over your approach:

  • it doesn't connect to DB (time and resource consuming)
  • it is timezone-flexible (see valid timezones list)
  • you can change the resulting format any time you want

BTW: I strongly recommend reading this post on SO regarding date, time databases related best practises.

Upvotes: 1

Milind
Milind

Reputation: 71

You can use php function strtotime

<?php
    echo date("d-m-Y", strtotime("$todt")); 
?>

Try this hope it will works

Upvotes: 0

Kishan Kikani
Kishan Kikani

Reputation: 41

you can use if you want year like 2015 than use 'Y' in date formate

<?php
 $date = date('d-m-Y');
echo $date
?>

Upvotes: 0

Related Questions