zzlalani
zzlalani

Reputation: 24384

PHP How to reverse engineer the day of the year 3212 (YDDD) into 2013-08-01 (YYYY-mm-dd)

I have a date in YDDD format such 3212
I want to convert this date into default date string i.e. 2013-08-01 in PHP
Since the first value Y is the only character for Year, so I've decided to take the first three characters from the current Year i.e. 201 from 2013
The following is the code I've written for year

<?php
$date = "3212"
$y = substr($date,0,1); // will take out 3 out of year 3212
$ddd = substr($date,1,3); // will take out 212 out of year 3212
$year = substr(date("Y"),0,3) . $y; //well create year "2013"
?>

Now How can I use $year and 212 to convert it into 2013-08-01 using PHP

EDIT
FYI: My PHP Version is 5.3.6

Upvotes: 7

Views: 1384

Answers (4)

Andy Fleming
Andy Fleming

Reputation: 7865

// Formatted Date (YDDD)
$dateGiven = "3212";

// Generate the year based on the first digit
$year = substr(date("Y"),0,3).substr($dateGiven,0,1);

// Split out the day of the year
$dayOfTheYear = substr($dateGiven,1,3);

// Create a date object from the formatted date
$date = DateTime::createFromFormat('z Y',  "{$dayOfTheYear} {$year}");

// Output the date in the desired format
echo $date->format('Y-m-d');

View it online here: https://eval.in/private/69daafa849ee36

Upvotes: 2

salathe
salathe

Reputation: 51960

$date = "3212";
echo DateTime::createFromFormat("Yz", "201$date")->format("Y-m-d");
// 2013-08-01

Upvotes: 13

Mike Gallagher
Mike Gallagher

Reputation: 140

If you are running the code on PHP 5.3 or later, you can convert $year and $ddd to a usable date by using date_create_from_format. For example:

$date = date_create_from_format("Y-z", "$year-$ddd");
echo date_format($date, "Y-m-d");

Upvotes: 6

deceze
deceze

Reputation: 522480

$yddd = 3212;
preg_match('/^(\d)(\d{3})$/', $yddd, $m);

echo date('Y-m-d', strtotime("201{$m[1]}-01-01 00:00:00 +{$m[2]} days"));

Upvotes: 8

Related Questions