I want to pass my PHP server time to my JavaScript file.
PHP Code:
date_default_timezone_set('Australia/Perth');
echo date("r");
JavaScript:
$.get('time.php', function(data) {
today = new Date(data);
closing = new Date(data);
});
The PHP code returns Sun, 18 Mar 2012 12:01:23 +0800 which is correct time for Australia/Perth. But this returns an invalid JavaScript date object.
When I try to convert it to timestamp like:
echo strtotime(date("r"));
I get the JavaScript date Sun Mar 18 2012 04:03:14 GMT+0000 (WET) (this is the value of today js var)
If I use:
echo gmstrftime('%s');
I get: Sat Mar 17 2012 20:04:30 GMT+0000 (WET).
Can anyone please help me out?
The PHP code in Luna's answer with echo date isn't exactly like JavaScript code. This will mimic the JavaScript code exactly:
echo date('D M d Y H:i:s O');
You could also just leave the PHP code as it is and parse the date using JavaScript:
var date = new Date(Date.parse(DATE));
Then even things like this would work:
new Date(Date.parse('11 March 2017'));
Which outputs via a console log (GMT+1000 is because I am in Australia):
Sat Mar 11 2017 00:00:00 GMT+1000
More information is here: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
$.get('time.php', function(data) {
today = new Date(data);
closing = new Date(data);
});
What was the purpose of multiplying the string by 1000? That operation doesn't make sense.
This PHP will work for that.
echo date('D, d M y H:i:s')." +0000";
date('D M d Y H:i:s O')
It won't work if your current locale isn't English.
A better alternative is to use:
new Date(<? echo date("Y, n - 1, d, H, i, s") ?>)
Here is an example with the DateTime object:
PHP code (works on PHP 5.3 or later)
$serverDate = new \DateTime('NOW');
// If you want to set a different time zone
// $serverDate = new \DateTime('NOW', new \DateTimeZone('Australia/Perth'));
echo $serverDate->format(DATE_ATOM);
JavaScript code
$.get('time.php', function(data) {
var serverDate = new Date(data);
});
A good way is timestamp:
echo $data = time()*1000;
echo '
<div id="setxDatetime">The current server time is: </div>
<script type="text/javascript">
var x = document.getElementById("setxDatetime");
x.innerHTML = x.innerHTML + new Date(' . $data . ');
</script>
';
1381324693000
The current server time is: Wed Oct 09 2013 16:18:13 GMT+0300 (GTB Standard Time)
There might be better solutions, but this one did the trick for me. The key issue is that JavaScript uses months 0-11, while PHP uses 1-12 as mentioned previously.
function convert_date_php_js($date) {
$converted_date = date("Y", strtotime($date)) . ', ' .
(date("n", strtotime($date))-1) . ', ' .
date("j", strtotime($date));
return $converted_date;
}
$priceDate = "2016-09-14";
$d = convert_date_php_js($priceDate);
// Returns 2016, 8, 14
It is very simple:
new Date("<?= date('Y/m/d H:i:s'); ?>");
Related
This is the current date I got in PHP from getLastLogin():
Apr 22 2016, 01:44:17 CEST
This is the code that I use to convert it:
$ymd = null;
$dateObject = DateTime::createFromFormat('M d Y, H:i:s T', $player->getLastLogin());
if($dateObject){ $ymd = $dateObject->format("m/d/Y"); }
echo $ymd;
There is no error but it never goes into the if statement and therefore it's still null when I try to echo it.
My function getLastLogin() is working as well, so I think it's narrowed down to the actual format.
Thanks for help!
i have a strange questions.
In my php page i try to print dates with php function and javascript function.
My code is:
// 04 09 2013 09:47:28
<script>document.write(new Date());</script>
// 04 09 2013 09:48:17
<?php echo date('d m Y H:i:s');?>
Why the dates are not equal, but there is a litte second of difference?
I would have same dates beetween php and javascript.
---UPDATE CODE---
function startCounter(){
start = new Date(<?php echo time(); ?> * 1000);
end = new Date(<?php echo $end_ts; ?> * 1000);
timer = setInterval(updateCounter, refreshInterval);
}
function updateCounter(){
var now = new Date();
var distance = new Date(end - now);
}
Thank you very much.
First of all you need to understand the time being printed by php is the server time and time being printed by javascript is your local computer time. If the time between those 2 is different then it can show different time.
Like others said, javascript time is client time and php time is server time.
To solve the problem try something simliar to:
<? $time = time(); ?>
<script>document.write(new Date(<?=$time*1000?>));</script>
<?=date('Y-m-d H:i:s', $time')?>
I want to convert 1373892900000 to Monday 2013/07/15 8:55 AM in Codeigniter.
However, I keep receiving a totally different result by converting the timestamp using the function i have written, please note:I need to change the dates according to different timezones, that is why I want to write it this way:
public function time_convert($timestamp){
$this->load->helper('date');
date_default_timezone_set('UTC');
$daylight_saving = TRUE;
$timezone = "UM4"; //toronto or new york timezone
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$final_time = standard_date('DATE_RFC822', $time);
return $final_time;
}
Result from the above function is: Sat, 08 Dec 06 01:40:00 +0000
And if I don't put date_default_timezone_set('UTC'); in the above function, I get this date instead Sat, 08 Dec 06 02:40:00 +0100. My codeigniter seems to default the timezone to Europe/Berlin.
Can anyone please help me correct any of the mistakes I might have made?
Why not just use PHP's date function?
public function time_convert($timestamp){
return date('l Y/m/d H:i', $timestamp);
}
For different timezones use a DateTime object:
public function time_convert($timestamp, $timezone = 'UTC'){
$datetime = new DateTime($timestamp, new DateTimeZone($timezone));
return $datetime->format('l Y/m/d H:i');
}
Think that should work. Note: I tihnk you need at least PHP version 5.20 for the TimeZone class.
<?php
$time_str=1373892900000;
echo gmdate("fill with your format", $time_str);
?>
your format = format your time in php, reading this page for details.
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.gmdate.php
Appears as though an invocation of standard_date with the DATE_ATOM format may sort you:
echo unix_to_human(time(), true, 'us'); # returns 2013-07-12 08:01:02 AM, for example
There are a whole host of other options for the format, enumerated on the linked page.
This how to covert timestamp to date very simple:
echo date('m/d/Y', 1299446702);
to convert timestamp to human readable format try this:
function unix_timestamp_to_human ($timestamp = "", $format = 'D d M Y - H:i:s')
{
if (empty($timestamp) || ! is_numeric($timestamp)) $timestamp = time();
return ($timestamp) ? date($format, $timestamp) : date($format, $timestamp);
}
$unix_time = "1251208071";
echo unix_timestamp_to_human($unix_time); //Return: Tue 25 Aug 2009 - 14:47:51
if you want to convert it to a format like this: 2008-07-17T09:24:17Z than use this method
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
for details about date:
http://php.net/manual/en/function.date.php
Your timestamp is coming from javascript on the client, I would guess, because it appears to be in milliseconds. php timestamps are in seconds. So to get the answer you want, first divide by 1000.
Showing the full year would have made the issue more obvious, as you would have seen the year as 45,506.
I have a question that is making me crazy,
My Task is to parse a date from an API and transform it to RFC 822 format, because the feed that is coming out gets an validation error
the date from the API looks like this :
<review created="2012-10-23 14:51:12.0">
I have one Date in the description made via substr
$xtime = substr($review["created"], 0, 16);
$jahr = substr($xtime,0,4);
$mon = substr($xtime,5,2);
$tag = substr($xtime,8,2);
$datneu = $tag.'.'.$mon.'.'.$jahr;
this date will be rendered like :
23.10.2012
For the pubdate I made
$xtime = substr($review["created"], 0, 16);
$xxl = $pubtime . " GMT";
rendered like :
2012-10-23 14:51:12 GMT
And W3C feed validator says it´s not validate because pubDate is not in RFC 822 form
Sorry
This feed does not validate.
line 10, column 38: pubDate must be an RFC-822 date-time: 2012-10-29 11:51:23 GMT (5 occurrences) [help]
<pubDate>2012-10-29 11:51:23 GMT</pubDate>
and it needs to look like :
<pubDate>Wed, 02 Oct 2002 13:00:00 GMT</pubDate>
i can imagine a hacky solution for expressing sth like "if (month = 01){ actualmonth = Jan}" but i really don´t know how to do same with the days,
Also i´m not too comfortable with PHP but I need to solve this asap.
Hope you can help me, there must be a solution i didnt found at similiar questions
regards John
Have a look at DateTime::createFromFormat() or date_create_from_format.
http://fr2.php.net/manual/en/datetime.createfromformat.php
<?php
$date = date_create_from_format('Y-m-d H:i:s', '2012-10-23 14:51:12.0');
echo date_format($date, 'D, d M Y H:i:s');
?>
Have a look at the possible date formats
http://fr2.php.net/manual/en/function.date.php
EDIT: fixed
Hi in PHP you should look at this: function date
yeaaaaah that worked for me, amazing!
for others the exact solution for my Case was
$before = "2012-10-23 14:51:12.0";
$timetwo = substr($before, 0, 16);
$timethree = date_create_from_format('Y-m-d H:i:s', $timetwo);
$timefinal = date_format(timethree, 'D, d M Y H:i:s');
$after = $timefinal . ' GMT' ;
$after = "Mon, 23 Oct 2012 14:51:12 GMT";
thanks a lot for the quick answers you are awesome!
This worked for me....
date("r", strtotime($yourdate))
$yourdate was 2013-10-27 and I got Sun, 27 Oct 2013 00:00:00 +0000
What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?
date('Z');
returns the UTC offset in seconds.
// will output something like +02:00 or -04:00
echo date('P');
timezone_offset_get()
$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
Untested, but should work
I did a slightly modified version of what Oscar did.
date_default_timezone_set('America/New_York');
$utc_offset = date('Z') / 3600;
This gave me the offset from my timezone, EST, to UTC, in hours.
The value of $utc_offset was -4.
Simply you can do this:
//Object oriented style
function getUTCOffset_OOP($timezone)
{
$current = timezone_open($timezone);
$utcTime = new \DateTime('now', new \DateTimeZone('UTC'));
$offsetInSecs = $current->getOffset($utcTime);
$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}
//Procedural style
function getUTCOffset($timezone)
{
$current = timezone_open($timezone);
$utcTime = new \DateTime('now', new \DateTimeZone('UTC'));
$offsetInSecs = timezone_offset_get( $current, $utcTime);
$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}
$timezone = 'America/Mexico_City';
echo "Procedural style<br>";
echo getUTCOffset($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
echo "<br>--------------<br>";
echo "Object oriented style<br>";
echo getUTCOffset_OOP($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset_OOP($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
This is same JavaScript date.getTimezoneOffset() function:
<?php
echo date('Z')/-60;
?>
This will output something formatted as: +0200 or -0400:
echo date('O');
This may be useful for a proper RSS RFC822 format
<pubDate>Sat, 07 Sep 2002 00:00:01 -0500</pubDate>
GMT offsets (like this) shouldn't use a colon (+02:00 from date('P');).
And, although it is acceptable for RSS RFC833, we don't want output like PDT and CST because these are arbitraty and "CST" can mean many things:
CST = Central Standard Time
CST = China Standard Time
CST = Cuba Standard Time
date("Z") will return the UTC offset relative to the server timezone not the user's machine timezone. To get the user's machine timezone you could use the javascript getTimezoneOffset() function which returns the time difference between UTC time and local time, in minutes.
<script type="text/javascript">
d = new Date();
window.location.href = "page.php?offset=" + d.getTimezoneOffset();
</script>
And in page.php which holds your php code, you can do whatever you want with that offset value. Or instead of redirecting to another page, you can send the offset value to your php script through Ajax, according to your needs.