Carbon Date how to create date using string date and user language - php

how to create date using string date and user language
function createDate(string $date , string $culture)
{
Carbon::setLocale( $culture);
$datetime = Carbon::create($datetime );
return $date ->isoformat('L');
}
if current user in english work well
but if current user in french not working
$datetime='12/20/2022 10:20:20 '; $culture ="en" // en format MM/DD/YYYY =====\> OK
$datetime='20/12/2022 10:20:20 '; $culture ="Fr" // Fr format DD/MM/YYYY ======\>Exception

You can simply set a format for each input type (language) in an array and then use Carbon::createFromFormat.
function createFromInput(string $input, string $lang){
$inputFormat = ['en' => 'm/d/Y H:i:s', 'fr' => 'd/m/Y H:i:s', 'de' => 'd.m.Y H:i:s'];
return Carbon::createFromFormat($inputFormat[$lang],$input);
}
Examples for using the function:
$lang = 'en';
$input = '12/20/2022 10:20:20';
echo createFromInput($input, $lang);
//2022-12-20 10:20:20
$lang = 'fr';
$input = '20/12/2022 10:20:20';
echo createFromInput($input, $lang);
//2022-12-20 10:20:20
Variant for DateTime:
function createFromInput(string $input, string $lang){
$inputFormat = ['en' => 'm/d/Y H:i:s', 'fr' => 'd/m/Y H:i:s', 'de' => 'd.m.Y H:i:s'];
return DateTime::createFromFormat($inputFormat[$lang],$input);
}
$lang = 'en';
$input = '12/20/2022 10:20:20';
echo createFromInput($input, $lang)->format('Y-m-d H:i:s');
//2022-12-20 10:20:20
$lang = 'fr';
$input = '20/12/2022 10:20:20';
echo createFromInput($input, $lang)->format('Y-m-d H:i:s');
//2022-12-20 10:20:20
To try on https://3v4l.org/Q3hoA

Related

Unexpected data found date format?

There istimestamp field (not null) in UTC in database with value: 2019-08-09 20:06:08.
I tried to convert this time to local time using function:
private function toLocalTime($dateInUTC) {
$time = strtotime($dateInUTC.' UTC');
return date("d/m/Y H:i", $time);
}
Converting is:
$response = []; // Data is present here
foreach($response as $v) {
$v->created_at = $this->toLocalTime($v->created_at);
}
On line where I call $this->toLocalTime() I get exception:
I have tried this code:
$timestamp = '2019-08-09 10:41:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC');
$date->setTimezone('your/timezone'); //
$new_date = $date->format('your new format'); // Y-m-d H:i:s
Maybe my $timestamp is empty somewhere?
As I can see you have Carbon in your project:
$timestamp = '2019-08-09 10:41:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC');
$date->setTimezone('America/Argentina/Buenos_Aires'); // or your timezone
$new_date = $date->format('Y-m-d H:i:s'); // or your new format
in your example:
private function toLocalTime($dateInUTC)
{
// parse your date with carbon and set that as UTC
$date = Carbon::createFromFormat('Y-m-d H:i:s', $dateInUTC, 'UTC');
// set your timezone to get a local time.
$date->setTimezone('America/Argentina/Buenos_Aires'); // or your timezone
return = $date->format('Y-m-d H:i:s'); // or your new format
}
https://www.php.net/manual/en/timezones.php
If you don't have Carbon installed as your example using native php:
private function toLocalTime($dateInUTC)
{
$utc_date = \DateTime::createFromFormat('Y-m-d H:i:s', $dateInUTC), new DateTimeZone('UTC'));
$utc_date->setTimeZone(new \DateTimeZone('America/Argentina/Buenos_Aires'); // or your timezone
return $utc_date->format('Y-m-d H:i:s'); // or your new format
}

Why is this time difference when I use "IntlDateFormatter"?

Why is this time difference when I use "IntlDateFormatter"?
<?php
// php v7.1
$pattern = 'yyyy-MM-dd HH:mm:ss';
$timezone = "Europe/Budapest";
$inputDateTimeStr = '1890-01-01 00:00:00';
$locale = 'hu_HU';
$intlDateFormatter = new \IntlDateFormatter( $locale, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT, \IntlTimeZone::createTimeZone($timezone), \IntlDateFormatter::GREGORIAN, $pattern
);
$dateTime = new \DateTime($inputDateTimeStr);
$dateTime->setTimezone(new \DateTimeZone($timezone));
$outputDateTimeStr = $intlDateFormatter->format($dateTime->getTimestamp());
print ' in: ' . $inputDateTimeStr
. ' out: ' . $outputDateTimeStr // string(19) "1890-01-01 00:16:20"
. ' diff: ' . ( strtotime($outputDateTimeStr) - strtotime($inputDateTimeStr) ) . ' seconds';
Output: in: 1890-01-01 00:00:00 out: 1890-01-01 00:16:20 diff: 980 seconds
I think, the intlDateFormatter and DateTime are before 1890 not compatible.
The Middle European Time (MET) was introduced step for step in Europe after 1890.
At the beginning of 1890 each place had its own time, depending on its longitude.
The following code shows this for 4 examples.
$refDate = date_create('1890-01-01 UTC');
$ts = $refDate->getTimeStamp();
$pattern = 'yyyy-MM-dd HH:mm:ss';
$timezones = [
"Europe/Paris", //2.3522° E
"Europe/Berlin", //13.4050° E
"Europe/Prague", //14.4378° E
"Europe/Budapest"//19.0402° E
];
$locale = 'hu_HU';
foreach($timezones as $timezone){
$intlDateFormatter = new \IntlDateFormatter(
$locale,
\IntlDateFormatter::MEDIUM,
\IntlDateFormatter::SHORT,
\IntlTimeZone::createTimeZone($timezone),
\IntlDateFormatter::GREGORIAN,
$pattern
);
$outputDateTimeStr = $intlDateFormatter->format($ts);
echo $timezone.": ".$outputDateTimeStr."<br>";
}
Output
Europe/Paris: 1890-01-01 00:09:21
Europe/Berlin: 1890-01-01 00:53:28
Europe/Prague: 1890-01-01 00:57:44
Europe/Budapest: 1890-01-01 01:16:20
DateTime delivers other results.

php add method incorrectly working

I'm in the process of learning PHP and i'm having some trouble. My function is returning the "milestones" with the same date they were plugged in with. I believe I am using the add() method incorrectly. Thankyou.
PHPplayground: http://www.tehplayground.com/#cARB1wjth
$milestones = null;
$milestones = createMilestone($milestones, true, 10, "15-1-1", "birthday" );
var_dump( $milestones );
function createMilestone($milestones, $forward, $days, $startDate, $milestoneName ){
if ( is_string($startDate)){
$date = DateTime::createFromFormat("Y-m-d", $startDate );
}else if(is_array($startDate) ){
$date = $startDate["date"];
}else{
$date = $startDate;
};
$daysInterval = DateInterval::createFromDateString($days);
if ($forward){
$date->add($daysInterval);
}else{
$date->sub($daysInterval);
}
$milestones[$milestoneName]['date'] = $date;
return $milestones;
}
You need to use :
$daysInterval = DateInterval::createFromDateString($days . ' days');
See the doc here for DateInterval and that page for the diverse date formatting (called relative format) you can use.
And BTW, if you give a DateTime like "15-1-1", the correct format is not "Y-m-d" but "y-m-d" (lowercase 'y')

UTC Date/Time String to Timezone

How do I convert a date/time string (e.g. 2011-01-01 15:00:00) that is UTC to any given timezone php supports, such as America/New_York, or Europe/San_Marino.
PHP's DateTime object is pretty flexible.
$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');
PHP's DateTime object is pretty flexible.
Since the user asked for more than one timezone option, then you can make it generic.
Generic Function
function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
$date = new DateTime($date,new DateTimeZone($timezone));
$date->setTimezone( new DateTimeZone($timezone_to) );
return $date->format($format);
}
Usage:
echo convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');
Output:
2011-04-21 09:14:00
Assuming the UTC is not included in the string then:
date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00'; //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date; //Should get '2011-01-01 10:00:00 EST' or something like that
Or you could use the DateTime object.
function _settimezone($time,$defaultzone,$newzone)
{
$date = new DateTime($time, new DateTimeZone($defaultzone));
$date->setTimezone(new DateTimeZone($newzone));
$result=$date->format('Y-m-d H:i:s');
return $result;
}
$defaultzone="UTC";
$newzone="America/New_York";
$time="2011-01-01 15:00:00";
$newtime=_settimezone($time,$defaultzone,$newzone);
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* #return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];
$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];
datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
How about:
$timezone = new DateTimeZone('UTC');
$date = new DateTime('2011-04-21 13:14', $timezone);
echo $date->format;

Convert time and date from one time zone to another in PHP

Basically what I need is an script that, when provided with a time and a timezone can return the time in another time zone.
My main issues are:
Where to get the time offset from GMT from - is there a public database available for this?
How to also take into consideration the daylight saving time (DST) differences as well.
How to nicely wrap it all up inside an PHP class - or is there such a class already available?
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
found on DateTime Manual on php.net
EDIT:
Like Pekka said: The DateTime class exists from 5.2 on and there you first have to find out which of the methods are realy implemented and which one only exist from 5.3 on.
try this, it might help :)
function converToTz($time="",$toTz='',$fromTz='')
{
// timezone by php friendly values
$date = new DateTime($time, new DateTimeZone($fromTz));
$date->setTimezone(new DateTimeZone($toTz));
$time= $date->format('Y-m-d H:i:s');
return $time;
}
A bit description:
The function takes 3 inputs, time to convert, timezone to convert to, current timezone and returns the output in the specified format.
I know its late. For anyone who would want simple function to convert utc to any local time zone
function UTCTimeToLocalTime($time, $tz = '', $FromDateFormat = 'Y-m-d H:i:s', $ToDateFormat = 'Y-m-d H:i:s')
{
if ($tz == '')
$tz = date_default_timezone_get();
$utc_datetime = DateTime::createFromFormat($FromDateFormat, $time, new
DateTimeZone('UTC'));
$local_datetime = $utc_datetime;
$local_datetime->setTimeZone(new DateTimeZone($tz));
return $local_datetime->format($ToDateFormat);
}
echo UTCTimeToLocalTime('2015-07-01 13:30:00','America/Denver');
To convert from the given timezone to the desired timezone, we just have to add/subtract the difference of timezones (in SECONDS) to given timezone.
$my_timestamp = strtotime("2020-09-22 14:07:26");
/*
Convert timezones difference into seconds
from -7:00 to +5:30 have 12hrs and 30min difference
So in seconds, 12.5*60*60 is equaled to 45000 seconds
*/
$time_zone_difference = 45000;
//Use date function to get datetime in your desired formate
echo date("Y-m-d h:i:sa", $my_timestamp + time_zone_difference );
or we can write it like
Below given functions are for additional help.
Convert timezone differences in seconds, (which you can hardcode, if it is fixed throught the project):
function timezoneDifferenceInSec( $source_timezone, $required_timezone){
$a = explode(":",$source_timezone);
$b = explode(":",$required_timezone);
$c = (intval($a[0])*60+intval($a[1]))*60;
$d = (intval($b[0])*60+intval($b[1]))*60;
$diffsec =0;
if($c < $d)
$diffsec = $d-$c;
else
$diffsec = $c-$d;
return $diffsec;
}
//function call
$differenc = timezoneDifferenceInSec("-07:00", "+05:30");
Function to convert DateTime into required Timezone (if difference is known):
//datetime in String and timezone_differe is in int
function convertTimezone( $source_date_time, $timezone_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezone_diff_in_sec);
}
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);
Function to convert DateTime into required Timezone (if difference in seconds among the timezones is known):
example: Timestamp give is "2020-09-22 14:07:26".
Timezones difference in seconds id 4500; //ie from -07:00 to +05:30
// timestamp as in String and timezones_diff_in_sec is in int
function convertTimezone( $timestamp, $timezones_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezones_diff_in_sec);
}
Function call (
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);
Here i use this function for converting datetime into another timezone.
For best result if you convert your datetime into utc timezone and then convert into required timezone then it is better result for it.
function ConvertTimezoneToAnotherTimezone($time, $currentTimezone, $timezoneRequired) {
$dayLightFlag = false;
$dayLgtSecCurrent = $dayLgtSecReq = 0;
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d H:i:s");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecCurrent = -3600;
// }
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s ");
$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d H:i:s ");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecReq = +3600;
// }
date_default_timezone_set($system_timezone);
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
if ($dayLightFlag) {
$final_diff = $dayLgtSecCurrent + $dayLgtSecReq;
$date->modify("$final_diff seconds");
}
$timestamp = $date->format("Y-m-d H:i:s ");
return $timestamp;
}
Thank You.

Categories