When user enters Date and time using 'input type=date name="date"' && 'input type=time name="time"' tags according to his/her timezone,
for eg :- If a user from India, (Asia/Kolkata) timezone entered a date : 1/22/14 and time : 5:30pm , I need to Convert it into UTC time stamp for storing it to DB, To Achive that
I used below code:-
$year=substr($date,0,4);
$month=substr($date,5,2);
$day=substr($date,8);
$hour=substr($time,0,2);
$minute=substr($time,3);
$clientzone=mysql_result(mysql_query("select timezone from c_users_extra where c_id='{$_SESSION['clientid']}'"),0,0); //Fetches the timezone of user
date_default_timezone_set($clientzone);//Setting default timezone to client timezone
$datetime = new DateTime("$year-$month-$day $hour:$minute:00");
$la_time = new DateTimeZone('UTC');
$datetime->setTimezone($la_time);
$values=$datetime->format('Y-m-d H:i:s');
$year=substr($values,0,4);
$month=substr($values,5,2);
$hour=substr($values,11,2);
$minutes=substr($values,14,2);
$seconds=substr($values,17,2);
$timestamp=mktime($hour,$minutes,$seconds,$month,$day,$year);//creating new timestamp from coverted
print_r(getdate($timestamp));//Result : Array ( [seconds] => 0 [minutes] => 30 [hours] => 6 [mday] => 22 [wday] => 3 [mon] => 1 [year] => 2014 [yday] => 21 [weekday] => Wednesday [month] => January [0] => 1390372200 )
//Expected Result : Array ( [seconds] => 0 [minutes] => 0 [hours] => 12 [mday] => 22 [wday] => 3 [mon] => 1 [year] => 2014 [yday] => 21 [weekday] => Wednesday [month] => January [0] => 1390372200 )
Why I get this wrong time stamp ?
Here is an object oriented example:
<?php
$date = '2014-01-22 18:15:00'; // assumed date is formatted correctly
$clientzone = 'America/New_York'; // assumed timezone is a valid one from your SQL
$dateObj = new DateTime($date, new DateTimeZone($clientzone));
echo "Original: " . $dateObj->format('Y-m-d H:i:sP') . "\n";
$dateObj->setTimezone(new DateTimeZone('UTC')); // convert to UTC
echo "Converted: " . $dateObj->format('Y-m-d H:i:sP') . "\n";
echo "Epoch: ".$dateObj->format('U');
?>
You can format that just like the date function.
The $date and $clientzone are assumed to be valid.
Can't you do something simpler like:
$user_time = strtotime($date);
$dateTimeZone = new DateTimeZone($timezone);
// get the offset from server time (UTC)
$tzOffset = $dateTimeZone->getOffset(new DateTime());
$result_time = $user_time - $tzOffset;
Try following function to convert Local date time to UTC date time
function LocaltoUTC($date_to_convert)
{
$local_timestamp = strtotime($date_t);
$UTC_timestamp += ((-(5.5)) * 3600); // 5.5 is UTC timezone or local timezone
$gmt_datetime = gmdate('y-m-d H:i:s', $UTC_timestamp);
return $gmt_datetime;
}
Here is a similar question. Take a look at Adjusting time zone in PHP with DateTime / DateTimeZone
There is a solution and a more comfortable way to do your task.
Related
I'm having trouble understanding how my code adapts to DST, as it's incorrect with the recent update. I'm storing a date time in the database based on UTC and then converting it back to the local timezone for display. If PHP is taking DST into account, something else is wrong because all of my stored dates are 1 hour off.
$stored_date = '2016-11-16 12:04:01'; // in UTC
$dateTime = new DateTime($stored_date, new DateTimeZone('UTC'));
$dateTimeZone = new DateTimeZone('America/New_York');
$dateTime->setTimezone($dateTimeZone);
print_r($dateTime);
Last week, before DST ended, this would have printed out 2016-11-16 08:04:01. This week, now that DST has ended, it prints out 2016-11-16 07:04:01. Why the hour difference if PHP is properly handing the DST shift?
It shouldn't matter the server settings (I don't think) because I'm explicitly doing the conversion within PHP, right?
I'm ready to start doing a check with PHP to see if DST is in effect and offsetting the conversion by 1 hour because I can't figure out why that hour isn't being automatically compensated for within the DateTime class.
New York city switches between these time zones:
Winter: EST (Eastern Standard Time) = UTC -5
Summer: EDT (Eastern Daylight Time) = UTC -4
According to timeanddate.com the switch will happen on 6th of November. Thus the result is correct: 12 - 5 = 7
In other words, PHP is perfectly aware of DST, as we can see in the following code:
$dateTime = new DateTime('2016-11-05 12:04:01', new DateTimeZone('UTC'));
$dateTime->setTimezone(new DateTimeZone('America/New_York'));
echo $dateTime->format('r') . PHP_EOL;
$dateTime = new DateTime('2016-11-06 12:04:01', new DateTimeZone('UTC'));
$dateTime->setTimezone(new DateTimeZone('America/New_York'));
echo $dateTime->format('r') . PHP_EOL;
Sat, 05 Nov 2016 08:04:01 -0400
Sun, 06 Nov 2016 07:04:01 -0500
You can inspect the exact information available in your system's time database:
$timeZone = new DateTimeZone('America/New_York');
print_r($timeZone->getTransitions(mktime(0, 0, 0, 1, 1, 2016), mktime(0, 0, 0, 12, 31, 2016)));
Array
(
[0] => Array
(
[ts] => 1451602800
[time] => 2015-12-31T23:00:00+0000
[offset] => -18000
[isdst] =>
[abbr] => EST
)
[1] => Array
(
[ts] => 1457852400
[time] => 2016-03-13T07:00:00+0000
[offset] => -14400
[isdst] => 1
[abbr] => EDT
)
[2] => Array
(
[ts] => 1478412000
[time] => 2016-11-06T06:00:00+0000
[offset] => -18000
[isdst] =>
[abbr] => EST
)
)
I receive a datetime from a plugin. I put it into a variable:
$datetime = "20130409163705";
That actually translates to yyyymmddHHmmss.
I would need to display this to the user as a transaction time but it doesn't look proper.
I would like to arrange it to be like 09/04/2013 16:37:05 or 09-apr-2013 16:37:05.
How do I go about and change the orders of the string?
As for now I could think is to use substr to separate the date and time. I'm still not sure on how to add the additional characters and rearrange the date.
why not use date() just like below,try this
$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);
and will be output
09/04/13 16:37:05
For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php
$datetime = "20130409163705";
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want
Result:
09/04/2013 16:37:05
date("Y-m-d H:i:s", strtotime("2019-05-13"))
If you want to use substr(), you can easily add the dashes or slashes like this..
$datetime = "20130409163705";
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;
You can figure out any further formatting from that point.
You have different options.
Using date():
$format = date('d/m/y H:i:s', 1621371929);
echo $format;
the output is:
18/05/21 14:05:29
Using date_format():
$date = date_create(1621371929);
echo date_format($date, 'd/m/y H:i:s');
the output is:
18/05/21 14:05:29
Using DateTime::format():
$date = new DateTime('2021-05-18 14:05:29');
echo $date->format('d/m/y H:i:s');
the output is:
18/05/21 14:05:29
This article gives you an overview of these three methods, and this one is DateTime::format() in depth.
try this
$datetime = "20130409163705";
print_r(date_parse_from_format("Y-m-d H-i-s", $datetime));
the output:
[year] => 2013
[month] => 4
[day] => 9
[hour] => 16
[minute] => 37
[second] => 5
You could do it like this:
<?php
$datetime = "20130409163705";
$format = "YmdHis";
$date = date_parse_from_format ($format, $datetime);
print_r ($date);
?>
You can look at date_parse_from_format() and the accepted format values.
https://en.functions-online.com/date.html?command={"format":"l jS \\of F Y h:i:s A"}
You can use date_parse_from_format() function ...
date_parse_from_format(string $format, string $datetime): array
Example
<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>
The above example will output:
Array
(
[year] => 2009
[month] => 1
[day] => 6
[hour] => 13
[minute] => 0
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] => 1
[zone_type] => 1
[zone] => 3600
[is_dst] =>
)
Check the PHP docs..you will get clear idea
How do you get today's date, as a date object?
I'm trying to compute the difference between some start date and today. The following will not work, because getdate() returns an array and not a date object:
$today = getdate();
$start = date_create('06/20/2012');
$diff = date_diff($start, $today);
echo($today . '<br/>' . $start . '<br/>' . $diff);
Output:
Array ( [seconds] => 8 [minutes] => 1 [hours] => 16 [mday] => 11 [wday] => 1 [mon] => 6 [year] => 2012 [yday] => 162 [weekday] => Monday [month] => June [0] => 1339455668 )
DateTime Object ( [date] => 2012-06-20 00:00:00 [timezone_type] => 3 [timezone] => America/Los_Angeles )
new DateTime('now');
http://www.php.net/manual/en/datetime.construct.php
Comparing is easy:
$today = new DateTime('now');
$newYear = new DateTime('2012-01-01');
if ($today > $newYear) {
}
Op's edit
I just needed to call date_default_timezone_set, and then this code worked for me.
To get difference in days use this:
$today = new DateTime('today');
the time in this object eill be 00:00:00
If you want difference with hours minutes and seconds use this:
$now = new DateTime('now');
I ended up using the date_create constructor (no parameter) to get the current date.
$diff = date_diff(date_create('06/20/2012'), date_create());
print_r($diff);
Output:
DateInterval Object ( [y] => 0 [m] => 0 [d] => 8 [h] => 6 [i] => 30 [s] => 40 [invert] => 1 [days] => 8 )
I have no idea why, but Mike B's answer (and any constructor I tried for DateTime) threw an error for me in PHP5 / IIS.
I was wondering how can I turn the following date into an array.
PHP code.
$current_date = date('Y-m-d H:i:s'); //current date
$current_date = array(date('Y-m-d H:i:s'));
The built-in php function strptime() converts a date to an array. See the linked documentation for details about the structure of the array it produces.
I think you want to get the components of the function return into an array.
// Method one
$current_date = array(date('Y'),date('m'),date('d'),date('H'),date('i'),date('s'));
// Method two
$current_date = date('Y-m-d H:i:s'); //current date
$exploded_current_date = explode(" ", $current_date);
$date = explode("-",$exploded_current_date[0]);
$time = explode(":",$exploded_current_date[1]);
$current_date = array_merge($date,$time);
Update:
// Method three
$current_date = getdate();
/*
Returns
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
*/
Here is an example.
<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));
?>
I have a date in the following format
November 18, 2009, 3:00PM
How can i break that up so that i can store each value as its own variable?
such as...
$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM
Use the 'date_parse' (http://nl2.php.net/manual/en/function.date-parse.php) function. It returns an array with the parsed items:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Convert your date into a timestamp, then with the timestamp you can easily get your parts. An other way is using a regular expression.
$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;
echo "\$month $month\n";
echo "\$day $day\n";
echo "\$year $year\n";
echo "\$hour $hour\n";
echo "\$minute $minute\n";
echo "\$ampm $ampm\n";
Output
$month November
$day 18
$year 2009
$hour 3
$minute 00
$ampm PM
More complex solution.
If your dates may be in the different standards you can use date() function (http://php.net/manual/en/function.date.php) + strtotime() function (http://php.net/manual/en/function.strtotime.php), which parse string and returns the unix timestamp.
For example, if you want to get a year from your date string you could write next code:
$date = 'November 18, 2009, 3:00PM';
$year = date('Y', strtotime($date));
Or, if you want to know how much days in the month in date you get, you could write such code:
$date = 'November 18, 2009, 3:00PM';
$num_of_days = date('t', strtotime($date));
't' returns the number of days in the given month.