How to update certain values of a php date string? - php

I have some date string values that I want to be able to update for checking against in some conditional statements. I want to update the hour, minute and seconds values to be at 23:59:59.
Say I have the variable $value which prints to
2017-03-08 00:00:00
How can I update the value to be
2017-03-08 23:59:59
?

Use DateTime.
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s',$value);
$dateTime->setTime(23,59,59);
$value = $dateTime->format('Y-m-d H:i:s');
http://php.net/manual/en/class.datetime.php
You could do many more things with the DateTime class.

Hi there this is the code below which you can use to update the time value:
your variable in php:
$value = "2017-03-08 00:00:00";
the html tag like so:
<input type="datetime-local" name="date" value="<?php echo date("Y-m-d\TH:i:s", strtotime($value)); ?>" />
This tag also generates a date and time picker, assuming you a running a compatible browser.
Note: In the future please show us your work and what you have achieved because you cannot expect someone to do it all for you, good luck!

In this simple case, you could probably leverage strtotime to get what you want:
$myDate = '2017-03-08 00:00:00';
$myTime = strtotime($myDate) + 86399;
echo date('Y-m-d H:i:s', $myTime);
Though in more difficult cases it would probably be better to use PHP's DateTime class:
$myDate = '2017-03-08 00:00:00';
$dt = new DateTime($myDate);
// Subtract one second
$dt->add(new DateInterval('PT86399S'));
// Output formatted result
echo $dt->format('Y-m-d H:i:s');
You could also look into Carbon for handling all of your date / time needs.

Related

php adding 1 hour to the timestamp

I am trying to add 1 hour to a timestamp field fetched from database using the following code.
date($ls['created_at'], strtotime('+1 hour'));
However, this doesn't seem to work. It returns the same time as in database. Am I missing something? Or, is the code deprecated? What is the proper solution?
You need to give it the correct syntax to use this,
You need to send the time to change with the change itself in the function - for example (using date for wanted format):
$date = "22-02-2021 14:22:22";
echo date("d-m-Y H:i:s", strtotime($date.' +1 hour'));
This will return:
22-02-2021 15:22:22
Same as this:
echo date("d-m-Y H:i:s", strtotime("22-02-2021 14:22:22 + 1 hour"));
The idea is that you strtotime receives the date and data to change in one string like this :
echo strtotime("22-02-2021 14:22:22 + 2 hour");
Will return:
1614010942
Here I removed the Date Format so I received a unix timestamp format

How to convert T-Z string to australian time? [duplicate]

So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function?
Thanks!
I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.
For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).
If I understood correct,You need to set time zone first like:
date_default_timezone_set('UTC');
And than you can use date function:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y # G:i');
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::format.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
It should like this:
date_default_timezone_set('America/New_York');
U can just add, timezone difference to unix timestamp.
Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
Try this. You can pass either unix timestamp, or datetime string
public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s')
{
$datetime = is_numeric($timestamp) ?
DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
new DateTime($timestamp, new DateTimeZone($fromTimezone));
$datetime->setTimezone(new DateTimeZone($toTimezone));
return $datetime->format($format);
}
this works perfectly in 2019:
date('Y-m-d H:i:s',strtotime($date. ' '.$timezone));
I have created this very straightforward function, and it works like a charm:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.
$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");
This returns the current local time in Jakarta, Indonesia.
Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading # sign.
$dt = new DateTime('#123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');
See the documentation about compound formats:
https://www.php.net/manual/en/datetime.formats.compound.php
Based on other answers I built a one-liner, where I suppose you need current date time. It's easy to adjust if you need a different timestamp.
$dt = (new DateTime("now", new DateTimeZone('Europe/Rome')))->format('d-m-Y_His');
If you use Team EJ's answer, using T in the format string for DateTime will display a three-letter abbreviation, but you can get the long name of the timezone like this:
$date = new DateTime('2/3/2022 02:11:17');
$date->setTimezone(new DateTimeZone('America/Chicago'));
echo "\n" . $date->format('Y-m-d h:i:s T');
/* Displays 2022-02-03 02:11:17 CST "; */
$t = $date->getTimezone();
echo "\nTimezone: " . $t->getName();
/* Displays Timezone: America/Chicago */
$now = new DateTime();
$now->format('d-m-Y H:i:s T')
Will output:
29-12-2021 12:38:15 UTC
I had a weird problem on a hosting. The timezone was set correctly, when I checked it with the following code.
echo ini_get('date.timezone');
However, the time it returned was UTC.
The solution was using the following code since the timezone was set correctly in the PHP configuration.
date_default_timezone_set(ini_get('date.timezone'));
You can replace database value in date_default_timezone_set function,
date_default_timezone_set(SOME_PHP_VARIABLE);
but just needs to take care of exact values relevant to the timezones.

PHP date limit 1970

I'm programming a site about genealogy, I used the date input to acquire dates, and
$datamm= strftime('%Y-%m-%d', strtotime($_POST['datamm']));
to convert the dates for the database, but the minimum value that I can get is 1970-01-01. I need to acquire dates between 1500 and current day.
What can I do to solve the problem?? I prefer procedural solution if it is possible.
Here is an example,
<?php
$date = new DateTime( '01-01-1950' );
echo $date->format( 'Y-m-d' );
?>
DateTime is great, you can do all sorts once you understand it.
For instance, this will add a year and echo the start and end dates,
<?php
$date = new DateTime( '01-01-1950' );
echo $date->format( 'Y-m-d' )."\n";
$date->modify( '+1 years' );
echo $date->format( 'Y-m-d' );
?>
If you know that in which format your date is coming from input then you can try:
$datamm = DateTime::createFromFormat('j-M-Y', $_POST['datamm']);//You know that date is coming in j-M-Y format
echo $date->format('Y-m-d'); // You can save in Y-m-d format in database
if you are taking timestamp as input then :
$date = date('Y-m-d',$_POST['datamm']);//you are taking timestamp like : 30000000000 as an input
echo $date;//make in database in Y-m-d format
I hope it helps
Try this, use createFromFormat
// pass your date format
$date = DateTime::createFromFormat('d M Y','17 Jan 1500');
echo $date->format('Y-m-d');
DEMO
You should probably focus on using some 3rd party library instead of official PHP's datetime functions.
For example, for your advanced date-time manipulating requirements, a good alternative for PHP's standard datetime would be moment.php
It's inspired by moment.js library whose goal is to fix common date-time programming issues, and bring standardization to higher level.
You can obtain it via composer like:
{
"require": {
"fightbulc/moment": "*"
}
}
Or via github for manual installation.
To parse various input date consult a manual, below is example:
$m = new \Moment\Moment('1503-04-25T03:00:00', 'CET');
There is also other alternatives to explore, for example:
https://github.com/swt83/php-date

Convert User Submitted Date To UTC

I'm trying to figure out how to accept a date/time from a form, which is consequently in the user's timezone, and change it to UTC before inserting it into the database. For some reason, no amount of searching has netted me an answer.
My form will POST whatever date is selected by the user to my code, so I expect to be able to do something like this. Note: the $userDate may be relative to any number of timezones based on user's location
$userDate = $_POST['user_date'] // 2014-05-15 16:37:23
I anticipate using Date().getTimezoneOffset() on my form to also submit the users UTC offset (as detailed here).
$userOffset = $_POST['user_offset']
Then before inserting the date into my database, I would like to convert it to UTC -- but I am stumped on how to do that with PHP (I'm actually using Laravel so if you know of a way using Carbon, that would be even easier, but I couldn't find it in their docs).
I've been half tempted to manually parse the offset and convert it to number of seconds and add or subtract it to strtotime() output of the $userDate and then convert it back into a date format using date() -- but there has to be a better way!
What am I missing here? Does PHP have a function I just don't know about that lets me do something like:
$userDate = '2014-05-15 16:37:23';
$userOffset = '+04:00';
$utcDate = date_apply_offset($userDate, $userOffset);
echo $utcDate; // Outputs: 2014-05-15 20:37:23
Or am I making this harder than it has to be?
EDIT
Based on the solution provided by #vascowhite, I went with the following (added into question to improve answers for those seeking guidance)
I ended up using a function from moment.js since I was already using it to convert UTC to user's timezone on display.
HTML:
<input id="user_offset" type="hidden" name="user_offset" value="">
Javascript:
var offset = moment().format('ZZ');
$('#user_offset').val(offset);
PHP (in a custom date class):
class MyDate {
/**
* Convert Date to UTC
*
* #param string $date Any date parsable with strtotime()
* #param string $offset UTC offset of date
*/
public static function toUTC($date, $offset = '+0:00')
{
if ($timestamp = strtotime($date) && ! empty($offset) )
{
$newDate = date('Y-m-d H:i:s', $timestamp);
$newDate = new \DateTime($date . ' ' . $offset);
$newDate->setTimezone(new DateTimeZone('UTC'));
$date = $newDate->format('Y-m-d H:i:s');
}
return $date;
}
}
// To convert
$userDate = trim($_POST['user_offset']);
$userOffset = trim($_POST['user_date']);
$utc = MyDate::toUTC($userDate, $userOffset)
That class method isn't perfect, and in the event something goes wrong, it just returns the date back -- when really it should throw an exception.
This is a simple task with the DateTime classes:-
$userDate = '2014-05-15 16:37:23';
$userOffset = '+04:00';
$date = new \DateTime($userDate . ' ' . $userOffset);
var_dump($date);
$date->setTimezone(new \DateTimeZone('UTC'));
var_dump($date);
You can then format the date as you wish for output eg:-
echo $date->format('Y-m-d H:i:s');
or:-
$utcDate = $date->format('Y-m-d H:i:s');
echo $utcDate; // Outputs: 2014-05-15 20:37:23
See it working.
If you are doing any work with dates and times in PHP it is worth taking the time to become familiar with these extremely useful classes.
For all sorts of date/time manipulations you can make use of moment.php
For your example all what is needed are two lines of code:
$m = new \Moment\Moment('2014-05-15 16:37:23', '+0400');
echo $m->setTimezone('UTC')->format(); // 2014-05-15T12:37:23+0000
There is much more which helps to deal with date/time issues: https://github.com/fightbulc/moment.php
Cheers

Format DATETIME from MYSQL database using PHP

So I have a field in my database called 'DateTime' and the following lines of code:
echo "Date/Time: ";
echo $row['DateTime'];
How do I format it so that instead of being like this:'2013-02-07 22:14:56', it will be like this: '07/02/13 - 22:14'
Thanks.
Alternatively you could use:
DateTime::createFromFormat('Y/m/d H:i:s',$row['DateTime']); this will give you a datetime object, which are quite nice to work with.
Another alternative would be to have MySQL format the DATETIME value as a string in the desired format, using the DATE_FORMAT function.
SELECT DATE_FORMAT(`DateTime`,'%d/%m/%y - %H:%i') AS `DateTime`
...
No change required to your PHP code except for the SQL text sent to the database server.
This approach can very efficient, and reduce the amount of code you need, if all you are doing with this string is displaying it. If you are doing any sort of manipulation on this value, then casting the string value returned from MySQL resultset into a datetime object is probably a better way to go.
A demonstration of the DATE_FORMAT function:
SELECT DATE_FORMAT('2013-02-07 22:14:56','%d/%m/%y - %H:%i') AS `DateTime`
DateTime
----------------
07/02/13 - 22:14
how to output date into Year textbox Month textbox Day textbox
$book_date = $myrow["Publication_Day"];
$book_year = Date("Y", strtotime($book_date));
$timestamp contains ur date & time in any format.....................
date('Y/m/d - H:i',strtotime($timeStamp));
echo date('d/m/y H:i', strtotime($row['DateTime']));
See date and strtotime for more detail on the functions from the docs
$mytime = strtotime('2013-06-07 22:14:56');
$newDate = date('m/d/y - G:i', $mytime);
echo $newDate;
Here's an alternative using DateTime. If you're working with timezones this code can be easily modified to handle that.
$datetime = new DateTime('2013-02-07 22:14:56');
echo $datetime->format('d/m/y H:i');
See it in action

Categories