convert french datetime to datetime us - php

I want to convert in php a datetime fr ( 30/11/2016 12:30 ) to a datetime US (2016-11-30 12:30)
Should I use explode then implode or is there a better solution to convert it ?

I highly discourage use of "String Functions(str_replace etc.)" to modify datetime strings. Even procedural way should be avoided.
Correct way is to use DateTime class and ofcourse OOP way:
$time = '30/11/2016 12:30';
$date = DateTime::createFromFormat('d/m/Y H:i', $time);//assuming you are using 24 hour format for time
$time = $date->format('Y-m-d H:i');
echo $time;//2016-11-30 12:30
For more insight, please check:
http://php.net/manual/en/datetime.createfromformat.php
I hope it helps

$french_date_string = '30/11/2016 12:30';
$french_date_string = str_replace('/', '-', $french_date_string);
$date = new DateTime($french_date_string);
echo $date->format('Y-m-d H:i');
This code also works. But as far as I'm concerned, Abhay Maurya's answer seems to be more reliable and perfect way of working with datetime with the dedicated datetime classes and functions.

Related

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

PHP, use strtotime to subtract minutes from a date-time variable?

I need to subtract 45 minutes from the date-time variable in PHP.
The code:
$thestime = '2012-07-27 20:40';
$datetime_from = date("Y-m-d h:i",strtotime("-45 minutes",strtotime($thestime)));
echo $datetime_from;
returns the result 2012-07-27 07:55.
It should be 2012-07-27 19:55, though. How do I fix this?
You should do:
$datetime_from = date("Y-m-d H:i", strtotime("-45 minutes", strtotime($thestime)));
Having H instead of h means a 24-hour format is used, representing the hour with leading zeros: 00 through 23.
You can read more on this in the PHP date function documentation.
There are also object oriented ways of doing this which are more fluent, like DateTime::sub:
$datetime_from = (new DateTime($thestime))->sub(DateInterval::createFromDateString('45 minutes'))->format('Y-m-d H:i')
Or the even more expressive way offered by the Carbon library which extends PHP's built in DateTime class:
$datetime_from = (new Carbon($thestime))->subMinutes(45)->format('Y-m-d H:i');

How to convert timestamp into date/time string in PHP?

I need to construct a DateTime from an integer Unix timestamp 1329272833. The documentation says the constructor needs a "date/time" string like 2006-04-12T12:30:00. I manually did my own conversion:
$dateTimeEnd = new DateTime(
date('Y-m-d\TH-i-s', 1329272833)
);
Does PHP have a built in function to do this conversion?
You can use a timestamp as parameter if you add the #-sign at the front:
$dateTimeEnd = new DateTime('#1329272833'); # 2012-02-15 02:27:13+00:00
Demo. You find it documented on the manual page, see the examples.
$dateTimeEnd = DateTime::createFromFormat('U', 1329272833);
See DateTime::createFromFormat()
$date = new DateTime();
$date->setTimestamp(1171502725);
Datetime::setTimestamp()
All the comments above don't answer the question "how to convert timestamp to datetime STRING", they answer the question "how to convert timestamp to datetime OBJECT"
Given that $dateTime->date doesn't work, it seems to me the answer is not so obvious.
Probably
$date = new DateTime();
$date->setTimestamp(1171502725);
$date_string = date_format($date, 'U = Y-m-d H:i:s')
would be an answer.
Not sure it's optimal though. And looks ugly.

Converting date to this format

I have a date in this format:
24-12-2010 // DAY - MONTH - YEAR
I need to get it in this format:
1995-12-31T23:59:59.999Z // The Z is for the TimeZone I think.
Check this link out:
http://lucene.apache.org/solr/api/org/apache/solr/schema/DateField.html
The above link is the way I need the date.
I am using PHP now, so this needs to be with PHP.
How can I convert these dates the easiest way?
Thanks
That is an ISO8601 format date; the following is what you want.
gmdate('Y-m-d\TH:i:s\Z', strtotime($date_value));
You can do something like that:
$dateTime = new DateTime($myDate);
$formatted = $dateTime->format("Y-m-d\TH:i:s.z\Z");
The mentioned solution with:
$dateTime->format(DateTime::W3C);
$dateTime->format(DateTime::ISO8601);
does return strings like:
2012-11-28T17:21:11+0100
which cannot be parsed, at least with newer Solr versions.
I wouldn't use gmdate if you need to support timezones. The DateTime implementation is well done, and is also available for functional programming.
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/ref.datetime.php
You can use the DateTime class
$dateTime = new DateTime();
$dateTime.setDate(24, 12, 2010);
$output = $dateTime.format(DateTime::W3C);
// Output now is your date in W3C format.
use the date ( string $format [, int $timestamp ] ) function of php!
In second paramter use http://php.net/manual/en/function.strtotime.php to get the timestamp from strings
$date = strtotime('24-12-2010');
$new_date = gmDate("Y-m-d\TH:i:s.z\Z",$date);

Categories