Get Year/Month/Day separately from MySQL datetime in PHP - php

I store user register date and time as datetime in MySQL. now to do some process with that date i need to get year, month and day separately to work with.
for example:
2015-07-30 19:20:34
now I want 2015, how do I do that in PHP?

date('Y', strtotime(<date string from mysql>));
The strtotime function (http://php.net/manual/en/function.strtotime.php) parses your date string to a Unix timestamp, and then the date function (http://php.net/manual/en/function.date.php) outputs it in the defined format.
So you can do something like:
$date = '2015-07-30 19:20:34';
$year = date('Y', strtotime($date));

I'm not sure but try this:
<?php
$str="2015-07-30";
$explode=explode("-",$str);
echo $explode[1];
?>

$datetime = date_create("2015-07-30 19:20:34");
$day = date_format( $datetime, 'l'); // Thursday
$date = date_format( $datetime, 'd'); // 30
$month = date_format( $datetime, 'F'); // July
$year = date_format( $datetime, 'Y'); // 2015
function.date php
datetime.format.php

It is very simple, you can use strtotime() function of PHP like this:
$dated=$row['timestamp'];// in this case '2015-07-30 19:20:34';
$FullYear=date('Y',strtotime($dated)); // result 2015
$FullYear=date('y',strtotime($dated)); // result 15

date('Y', strtotime(<date string from mysql>));
$date = '2015-07-30 19:20:34';
$year = date('Y', strtotime($date));
It should work.

Related

How can i convert date("j/n/y") to epoch

I have some data that makes use of date("j/n/y") format i.e date for today is 23/1/15
I have tried
echo strtotime($today);
but this does not give me the timestamp i want.How would i convert a date in date("j/n/y") format to epoch?.
Use DateTime::createFromFormat() to read the date format and then use DateTime::getTimestamp() to format it as a timestamp.
$date = DateTime::createFromFormat('j/n/y', '23/1/15');
$epoch = $date->getTimestamp();
I think you're looking for the mktime function in PHP. It goes a little like this:
$timestamp = mktime(0,0,0,0,0,0);
Where, in order, the arguments are: hour, minute, second, month, day, year. So, in your case:
$today = mktime(0, 0, 0, 1, 23, 2015);
// Would return the timestamp for Jan. 23rd, 2015 at 12:00:00 am (I think)
If you're looking for a dynamic right now timestamp, you may use date() in each of the arguments of mktime. For example:
$rightnow = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
// Would return the timestamp for Jan. 23rd, 2015 at 10:57:25 am.
But, as John Conde says, it requires you break apart the date before you can use it, so it may not be as efficient.
Hope that helps!
Just to have another approach this one would be good for 85 more years.
$date = date('j/n/y', time());
list($day, $month, $year) = explode("/", $date);
$date = "20" . $year . "-" . $month . "-" . $day;
echo date('m/d/Y', strtotime($date));

convert a date in this format '031012' into a date that I can add days to

I have a date in this format 030512 (ddmmyy).
But I'm having trouble with converting this to a date usable format I can add days to.
Basically.. I extracted the date above from a text file, Now I need to be able to add a number of days to it. But I am having trouble parsing the date in this format.
Is there another way of doing this rather then something like this:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
$date_after = $day . "-" . $month . "-".$year;
// Now i need to add x days to this
$total_no_nights = 010; // must be this format
$days_to_add = ltrim($total_no_nights,"0"); // 10, remove leading zero
// how do i add 10 days to this date.
You can do this (php >= 5.3):
$date = DateTime::createFromFormat('dmy', '030512');
$date->modify('+1 day');
echo $date->format('Y-m-d');
http://www.php.net/manual/en/datetime.createfromformat.php
For php < 5.3 :
$dateArray = str_split('030512', 2);
$dateArray[2] += 2000;
echo date("d/m/Y", strtotime('+1 day', strtotime(implode('-', array_reverse($dateArray)))));
try this using the month/day/year you already have:
$date = "$month/$day/$year";
$change = '+10 day';
echo date("d/m/Y", strtotime($change, strtotime($date)));
Assuming the date will always be in the future (or at least after 1st Jan 2000), you're not far wrong:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
// dd-mm-yy is not a universal format but we can use mktime which also gives us a timestamp to use for manipulation
$date_after = mktime( 0, 0, 0, $month, $day, $year );
// Now i need to add x days to this
$total_no_nights = "010"; // must be this format
$days_to_add = intval( $total_no_nights ); // No need to use ltrim
// Here's the "magic". Again it returns a timestamp
$new_date = strtotime( "+$days_to_add days", $date_after );
Using the DateTime object would be easier but you say you're not on PHP5.3.
You can't do date manipulation with strings becase, well, they are not dates. In PHP, you can use Unix timestamps (which are actually integers...) or DateTime objects. In you case:
$timestamp = strtotime('-10 days', mktime(0, 0, 0, $month, $day, $year));
echo date('r', $timestamp);
... or:
$object = new DateTime("$year-$month-$day");
$object->modify('-10 days');
echo $object->format('r');
Also, please note that 010 is an octal number that corresponds to 8 in decimal.
using the convert function in sql the date can be obtained in appropriate format.
anter that operations can be performed in php to manipulate the date. i hope that answers your query.

parse UTC timestamp in PHP for only year, month, and date?

what is the best way to take a UTC timestamp (integer) and parse it for only the year, month, and day in PHP? Thanks
Use the PHP date() function.
<?php
$timestamp = strtotime("2011-9-12 05:48:00");
$year = date('Y', $timestamp);
$month = date('m', $timestamp);
$day = date('d', $timestamp);
$newTimestamp = mktime(0, 0, 0, $month, $day, $year);
DateTime class is pretty good for this kind of task
<?php
// for PHP5.2+ though
var_dump(date_create('2011-9-12 05:48:00')->setTime(0, 0, 0)->format('U'));
// if input is in integer already
$input = 1315806480;
var_dump(date_create("#{$input}")->setTime(0, 0, 0)->format('U'));
<?php
$time = strtotime(date('Y-m-d', *timestamp*));
?>
EDITED:
The date() function takes your timestamp and represents it in a human readable string with only the year, month, and date (i.e. "2014-07-25") and omitting the hour, minutes, and seconds.
Then the strtotime() function takes that human readable string and turns it back into your timestamp, effectively making the time at 00:00 on that day.

PHP - Adding 7 days to a date the proper way [duplicate]

I want to add number of days to current date:
I am using following code:
$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
But instead of getting proper date i am getting this:
2592000
Please suggest.
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/function.date.php
and their function signatures.
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = new DateTime();
$date->modify('+1 week');
print $date->format('Y-m-d H:i:s');
or print date('Y-m-d H:i:s', mktime(date("H"), date("i"), date("s"), date("m"), date("d") + 7, date("Y"));
$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
You could also try:
$date->modify("+30 days");
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));
I know this is an old question, but for PHP <5.3 you could try this:
$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');
You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php
It however requires PHP 5.3.0.
$date = "04/28/2013 07:30:00";
$dates = explode(" ",$date);
$date = strtotime($dates[0]);
$date = strtotime("+6 days", $date);
echo date('m/d/Y', $date)." ".$dates[1];
You may try this.
$i=30;
echo date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
//add the two day
$date = "**2-4-2016**"; //stored into date to variable
echo date("d-m-Y",strtotime($date.**' +2 days'**));
//print output
**4-4-2016**
Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)
/**
* $date self explanatory
* $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
* $format the format for $date
**/
function addDate($date = '', $diff = '', $format = "d/m/Y") {
if (empty($date) || empty($diff))
return false;
$formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
$newdate = strtotime($diff, strtotime($formatedDate));
return date($format, $newdate);
}
//Aux function
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
Note: only for php >=5.3
Use the following code.
<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>
Reference has found from here - How to Add Days to Current Date in PHP
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.
Use the DateTime class
<?php
$date = new DateTime('2016-06-06'); // Y-m-d
$date->add(new DateInterval('P30D'));
echo $date->format('Y-m-d') . "\n";
?>
The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.
The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks
Source
Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:
$now = strtotime('31 December 2019');
for ($i = 1; $i <= 6; $i++) {
echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;
}
You'd get the following sequence of dates:
31 December
31 November
31 October
31 September
31 August
31 July
31 June
PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:
01 Dec 19
31 Oct 19
01 Oct 19
31 Aug 19
31 Jul 19
01 Jul 19

Add number of days to a date

I want to add number of days to current date:
I am using following code:
$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
But instead of getting proper date i am getting this:
2592000
Please suggest.
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/function.date.php
and their function signatures.
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = new DateTime();
$date->modify('+1 week');
print $date->format('Y-m-d H:i:s');
or print date('Y-m-d H:i:s', mktime(date("H"), date("i"), date("s"), date("m"), date("d") + 7, date("Y"));
$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
You could also try:
$date->modify("+30 days");
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));
I know this is an old question, but for PHP <5.3 you could try this:
$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');
You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php
It however requires PHP 5.3.0.
$date = "04/28/2013 07:30:00";
$dates = explode(" ",$date);
$date = strtotime($dates[0]);
$date = strtotime("+6 days", $date);
echo date('m/d/Y', $date)." ".$dates[1];
You may try this.
$i=30;
echo date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
//add the two day
$date = "**2-4-2016**"; //stored into date to variable
echo date("d-m-Y",strtotime($date.**' +2 days'**));
//print output
**4-4-2016**
Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)
/**
* $date self explanatory
* $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
* $format the format for $date
**/
function addDate($date = '', $diff = '', $format = "d/m/Y") {
if (empty($date) || empty($diff))
return false;
$formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
$newdate = strtotime($diff, strtotime($formatedDate));
return date($format, $newdate);
}
//Aux function
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
Note: only for php >=5.3
Use the following code.
<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>
Reference has found from here - How to Add Days to Current Date in PHP
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.
Use the DateTime class
<?php
$date = new DateTime('2016-06-06'); // Y-m-d
$date->add(new DateInterval('P30D'));
echo $date->format('Y-m-d') . "\n";
?>
The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.
The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks
Source
Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:
$now = strtotime('31 December 2019');
for ($i = 1; $i <= 6; $i++) {
echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;
}
You'd get the following sequence of dates:
31 December
31 November
31 October
31 September
31 August
31 July
31 June
PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:
01 Dec 19
31 Oct 19
01 Oct 19
31 Aug 19
31 Jul 19
01 Jul 19

Categories