$date = date_create('2013-10-27');// This is the date that inputed in textbox and that format is (Y-m-d)
$date = date_create('2013-10-10');// and if i click the button i want to force change the 27 to 10?
Should i use date_modify and do some loop or there's other way to change it in easy way rather than looping.
$in = date_create('2013-10-27');
// example 1
$out = date_create($in->format('Y-m-10'));
echo $out->format('Y-m-d') . "\n";
// example 2
$out = clone $in;
$out->setDate($out->format('Y'), $out->format('m'), 10);
echo $out->format('Y-m-d') . "\n";
// example 3
$out = clone $in;
$out->modify((10 - $out->format('d')) . ' day');
echo $out->format('Y-m-d') . "\n";
Demo.
You can use the native PHP "date_date_set" function to make this change.
$date = date_create('2013-10-27');
echo $date->format('Y-m-d');
2013-10-27
date_date_set($date,
date_format($date, 'Y'),
date_format($date, 'm'),
10);
echo $date->format('Y-m-d');
2013-10-10
Or using the Object-Oriented style:
$date = new DateTime('2013-10-27');
echo $date->format('Y-m-d');
2013-10-27
$date->setDate($date->format('Y'), $date->format('m'), 10);
echo $date->format('Y-m-d');
2013-10-10
Note: If you're just trying to modify the value of a day on the date that comes from a submitted <input> from a <form>. You could try these steps:
$date = '2013-10-27'; // pass the value of input first.
$date = explode('-', $date); // explode to get array of YY-MM-DD
//formatted results of array would be
$date[0] = '2013'; // YY
$date[1] = '10'; // MM
$date[2] = '17'; // DD
// when trigger a button to change the day value.
$date[2] = '10'; // this would change the previous value of DD/Day to this one. Or input any value you want to execute when the button is triggered
// then implode the array again for datetime format.
$date = implode('-', $date); // that will output '2013-10-10'.
// lastly create date format
$date = date_create($date);
$date = date("Y-m-d", strtotime("2013-10-10"));
Updated:
to force to change the day from 27 to 10
1) get the year and month
$date = date("Y-m-", strtotime( $_POST['user_selected_date'] ));
2) append your day
$date .= '10';
Also you can finish it in ONE step
$date = date("Y-m-10", strtotime( $_POST['user_selected_date'] ));
Use PCRE Function
$date = '2013-10-27';
$new_date = preg_replace("/\d{2}$/", "10", $date);
preg_replace manual
Related
I have two fields which store data like 2018-03-26 11:20:35 and 02:25:10(2 hours 25 minutes and 10 seconds) first data is date and time. second one is only time. I want to sum it and finally my result should 2018-03-26 13:45:45
How to do that in php code?
I have tried this way:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Output:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
Here's a simple solution, some checks are skipped:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
You could create a duration in seconds by comparing today at "00:00:00" and today at $hours. Actually, strtotime($hours) returns the timestamp of today at $hours, so, the addition of the two timestamp don't give the expected result.
If $hours is lesser than 24 hours, you could use:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Outputs:
2018-03-26 13:45:45
You should check DateTime::add:
http://php.net/manual/en/datetime.add.php
http://php.net/manual/en/datetime.examples-arithmetic.php
Example:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
It could be done with some simple string manipulation:
$dt = new DateTime("$date UTC");
$modify = preg_replace('/:/', ' hours ', $hours, 1);
$modify = preg_replace('/:/', ' minutes ', $modify, 1);
$modify .= ' seconds';
$dt->modify($modify);
demo
If you have MySQL as your data storage, you could do:
DATE_ADD(field1, INTERVAL field2 HOUR_SECOND)
demo
you can do something like:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
I'm assuming you only need the hours, and not minutes and seconds
EDIT:
you can do like that using regexp
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');
i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed
if i select 12 then output will be 2017-06-12 cause this date future date
final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month
i have tired but not working this
$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));
or
$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
thanks in your advance
One more option:
https://3v4l.org/Me2Kh
$input = 12;
$day = date("d");
if ($input > $day){
$date = date("Y-m-"). str_pad($input,2,"0", STR_PAD_LEFT);
}else{
$date = date("Y-m-",strtotime("+1 month")). str_pad($input,2,"0", STR_PAD_LEFT);
}
echo $date;
I use str_pad to keep two digit day number.
Try this -
<?php
$day = '05';
$today = date('Y-m-d');
$supplied = date('Y-m-'.$day);
if($today>$supplied){
$final = date('Y-m-d', strtotime("+1 months", strtotime($supplied)));
}
else{
$final = $supplied;
}
echo $today;
echo '<br />';
echo $supplied;
echo '<br />';
echo $final;
What I'm doing here -
Comparing the current and supplied date
Based on comparison, if supplied date is smaller, I'm adding 1 month else dislpaying the supplied date.
use this,
$today = date('Y-m-d');
$nextDate = date('Y-m-d', strtotime('+1 month'));
or $nextDate = date('Y-m-d', strtotime('+1 month', strtotime($today));
I think this may help.
I would consider using DateTime and it's add method for a DateInterval.
$date = new \DateTime('now', new \DateTimeZone('America/New_York'));
$interval = new \DateInterval('P1M');
$date->add($interval);
Here are the supported DateTimeZone values. Make sure to set that to the applicable time zone.
Edit:
DateTime is mutable, so please keep that in mind.
Try this code :
<?php
$selected_date = '2017-06-05';
$current = date('Y-m-d');
//echo $current;
if($selected_date < $current)
{
$newDate = date('Y-m-d',strtotime($selected_date."+1 month"));
echo $newDate; // gives 2017-07-05
}else if($selected_date > $current)
{
$newDate = $current;
echo $newDate; // gives 2017-06-07
}
?>
From what you described in the points at beginning of the question, you could achieve it this way:
$selectedDate = new DateTime('2016-06-05 00:00:00');
$now = new DateTime('now');
$now->setTime(0, 0, 0);
if ($selectedDate < $now) { // Selected date is in past
// Set month and year to current
$selectedDate->setDate(
date('Y'),
date('m'),
$selectedDate->format('d')
);
// Add 1 month
$selectedDate->add(new DateInterval('P1M'));
}
// If selected date is current or in future we do nothing
echo $selectedDate->format('Y-m-d');
For input 2017-06-05 it will return 2017-07-05 as expected, and for current or future date will return the date that was selected. Works also for any past date like 2016-04-05
$date =$row2['DeliveryDate'];
$date now contains the date variable as a datetime, to display it I would use:
echo date_format($date, 'm-d-y');
the problem I'm having is extracting single values from $date for example:
$datetime = strtotime($row2['DeliveryDate']);
$mysqldate = date("d", $datetime);
returns this error:
Warning: strtotime() expects parameter 1 to be string, object given in
C:\xampp\htdocs\tutorials\DerBlatt\hebrewDateTrial.php on line 10
I've tried numerous ways to extract the day/month/year into single variables but nothing works
if someone can suggest a way it might work I'll be very greatfull;
I've copy/pasted code from many sites but all of them use an example of the date as a string, unfortunately i haven't found a solution for the datetime variable.
I wanna do something like:
$date =$row2['DeliveryDate'];
//whatever conversion code that comes in between.
$d = //the day from datetime
$m = //the month from datetime
$y = //the year from datetime
If you are using PHP 5.3 or better ,use the DateTime class .
if you want to display in this format $format='m-d-y';
Retrieving data from database .
$date =$row2['DeliveryDate'];
$date = DateTime::createFromFormat('Y-m-d H:i:s',$date);
if($date){ // if the date is correct
$yourdate = $date->format($format);
$year = $date->format('Y');
$month = $date->format('m');
$day = $date->format('d');
}
Saving to database .
$date = DateTime::createFromFormat($format,$date);
if($date){
$date = $date->format('Y-m-d H:i:s');
$row2['DeliveryDate'] = $date;
}else{
$row2['DeliveryDate'] = date('Y-m-d H:i:s');
}
Try this:
echo date('d',strtotime($row2['DeliveryDate']));
i think it will work.
so this is how i made it work (very funny)...
$m = date_format($row2['DeliveryDate'], 'm');
$d = date_format($row2['DeliveryDate'], 'd');
$y = date_format($row2['DeliveryDate'], 'y');
echo 'Month: '.$m.' Day: '.$d.' Year: '.$y;
Thank you guys for helping me, sometimes my best solution is just using my head...
What date format is this?
2012-06-08dT00:00:00Z
And how can i convert a timestamp in php to this date format?
$dt = new DateTime('2012-06-08T00:00:00Z'); //with no 'd'
$timestamp = $dt->format('U');
If you must have the 'd', then:
$dt = DateTime::createFromFormat('Y-m-d??H:i:s?', '2012-06-08dT00:00:00Z');
$timestamp = $dt->format('U');
ETA: timestamp -> your format
$dt = new DateTime('#1339124400'); //the # indicates the following number is a timestamp
$isoformat= $dt->format('Y-m-d\TH:i:sZ'); //leave out the 'd' and escape the 'T'
here is something for you to start from:
$date = "2012-06-08dT01:02:03Z";
// parse the date correctly
$parsed_date = date_parse_from_format('Y-m-d H:i:s ', $date);
print_r($parsed_date);
// Make time from parsed date
$old_date = mktime($parsed_date['hour'], $parsed_date['minute'], $parsed_date['second'], $parsed_date['month'], $parsed_date['day'], $parsed_date['year']);
$now_date = time();
// a silly way to print that parsed date into the original way as before
echo date("Y-m-d", $old_date) . 'dT' . date("H:i:s", $old_date) . 'Z';
echo "\n";
// a silly way to print current date/time in that format
echo date("Y-m-d", $now_date) . 'dT' . date("H:i:s", $now_date) . 'Z';
I have $adate; which contains:
Tue Jan 4 07:59:59 2011
I want to add to this date the following:
$duration=674165; // in seconds
Once the seconds are added I need the result back into date format.
I don't know what I'm doing, but I am getting odd results.
Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.
If you are using php 5.3+ you can use a new way to do it.
<?php
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>
Just use some nice PHP date/time functions:
$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);
Given the fact that $adate is a timestamp (if that's the case), you could do something like this:
$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
Do this:
$seconds = 1;
$date_now = "2016-06-02 00:00:00";
echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);
I made this example for a timezone, but if you change some parts it may help you out:
$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;
Result:
2018/06/17 3:16:23========2018/06/17 3:15:53
It would be easier with DateTime::modify
(new DateTime($str))->modify("+$duration seconds"); //$str is the date in string
I have trouble with strtotime() to resolve my problem of add dynamic data/time value in the current time
This was my solution:
$expires = 3600; //my dynamic time variable (static representation here)
$date = date_create(date('Y-m-d H:i:s')); //create a date/time variable (with the specified format - create your format, see (1))
echo date_format($date, 'Y-m-d H:i:s')."<br/>"; //shows the date/time variable without add seconds/time
date_add($date, date_interval_create_from_date_string($expires.' seconds')); //add dynamic quantity of seconds to data/time variable
echo date_format($date, 'Y-m-d H:i:s'); //shows the new data/time value
font: https://secure.php.net/manual/en/datetime.add.php (consult Object Oriented style too, the Elzo Valugi solution)
(1) https://secure.php.net/manual/en/function.date.php