Parse date from javascript countdown (jQuery plugin) - php

I'm trying to parse "Time Left To Buy" from a Groupon clone. Don't worry, everything is legal. The Javascript looks like
var untilDate = new Date(1316206740000);
$("#wlt-DealTimeLeft .timer").countdown({until: untilDate,
layout: "<div class='timerDiv withDay clearfix'><div class='countdownItem days'><p>{dn}</p>{dl}</div><div class='countdownItem'><p>{hn}</p>{hl}</div><div class='countdownSep'>:</div><div class='countdownItem'><p>{mn}</p>{ml}</div><div class='countdownSep'>:</div><div class='countdownItem'><p>{sn}</p>{sl}</div></div>", onTick: function(periods){
$("#wlt-DealTimeLeft").uTimeLeftTick(periods,259080);
}});
I was thinking about the Date value, but it isn't only regular unix timestamp. How can I get the date when the deal ends? It's some kind of jQuery countdown plugin. Thank you for any hints or advices.

javascript Date objects take milliseconds, not seconds, so
var d= new Date(1316206740000);
document.write(d); //outputs Fri Sep 16 17:59:00 UTC-0300 2011

Related

How to get time with respect to MySQL timestamp, in ActionScript 3?

I want to show an ActionScript 3.0 Timer, with respect to a timestamp gotten from MySQL.
So suppose MySQL (PHP) returns a string like $my_birthday="2013-05-22 12:30:45"
I got it from ActionScript by a URLLoader, and I want to show the timer like this:
My age:
01 hours 01 minutes 42 seconds
What function should I use in:
public function timerHandler(e:TimerEvent)
{
log_textfield.text = String((new Date()).time) - my_birthday; // I need to convert the Date().Time to unix timestamp I guess, and a function for time difference.
}
This answer has a TimeSpan class that you may want to use. The code below should do what you need to get the TimeSpan where you can get the parts you need to display. I don't have Flash on this computer though to test, so your mileage may vary :)
// new Date() is allergic to dashes, it needs slashes.
my_birthday = my_birthday.replace('-', '/');
var sinceBirthday = TimeSpan.fromDates(new Date(), new Date(my_birthday));

Static countdown with javascript/php, how?

var austDay = new Date("May 18, 2012 00:00:00");
$('#countdown').countdown({until: austDay});
Is what I got. I wish to make this static, which I mean by it shows the same countdown in all timezones. So no matter if you change your timezone or your date on your pc, it should not affect the countdown and it should still be e.g 8 hours left.
Maybe this is not possible because Javascript is Client side?
What can I do? I really want it to live countdown and not so you need to refresh. Maybe I can use some help from PHP?
The countdown should be the same for example 4 hours left, it should also display that in new york and asia..
You can use PHP to pass the server time to the client like so.
var time = new Date(<?php echo time()*1000; ?>);
var austDay = new Date("May 18, 2012 00:00:00");
This creates a date object with the date and time shown, in the user's local timezone. To create a UTC date, you can do something like this instead:
var austDay = new Date(Date.UTC(2012, 4, 18));
...where 4 is the zero-based month number (2012 and 18 are the year and day, obviously).
If you need to display the date afterwards, use the "UTC" functions instead of their non-UTC counterparts, for example:
console.log(austDay.toUTCString()) // "Fri, 18 May 2012 00:00:00 GMT"
Another problem is that users could change their clocks. To give them something like "8 hours left" and be absolutely sure, you'd have to compare the server time to the client's time and set the date based on that.
For example, if the server knows that the thing happens at noon tomorrow, and it's 9:00 at night, then the countdown ends in 15 hours. You can tell the client how much time is left until the countdown is ready instead of passing them an absolute time.
var austDay = new Date();
var hoursLeft = <?php echo $something ?>;
austDay.addHours(hoursLeft);
You'd probably want to do it in seconds or smaller instead of hours, I used hours here for simplicity.

How to add +9 hours on my jQuery script?

How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.
I create the unix timestamp in a php file doing
$end = mktime(16, 54, 0, 8, 18, 2011);
and the copy it below
Countdown Script
<script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);
$(document).ready(function() {
$("#time").countdown({
date: end_date,
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>
Instead of playing the heroes by trying to do time Math (and even failing badly), you should rely on native methods, available to both PHP and JS:
// gets the time 9 hours from now
// you can give a 2nd parameter to specify when is "now"
$date = strtotime('+9 hours');
and:
// get the time right now
var date = new Date()
// add 9 hours, don't worry about jumping the 24hr boundary, JS resolves correctly.
date.setHours(date.getHours()+9)
Edit:
Since the OP said he wanted to use a TS from DB, here's the relevant code:
$date = strtotime('+9 hours', (int)$db_time);
Note: If $db_time is a formatted string, like "24 April 2011, 4:56 pm", you need to put the following code before the one above:
$db_time = strtotime($db_time);
However, I urge you to check for alternative ways to parse the time.
I'm going to read between the lines here a bit. I assume based on this and previous questions that you want a countdown for some event in the future and you're pulling a timestamp from a database and adding 9 hours to it to get the time of that future event.
Assuming this, you can't use most (any?) of the previous answers because of time zones and the fact that the user's clock might be more or less off. So if you calculate on the server that the event should fire at 5 o'clock and send that info to the user who's 3 time zones away from the server, the countdown will also be 3 hours off (because when it's 5 o'clock where the user is it's either 2 or 8 o'clock where the server is.)
The solution is to calculate the time left until the event and send that information to the browser. This way the countdown will be independent of the user's timezone or their computer's clock. For example if the event is at 5 o'clock and it's now 4 o'clock tell the browser to put 60*60*1=3600 seconds on the timer.
Using part of Christian's answer, do something like this on the server (assuming $db_time contains a Unix timestamp retrieved from the database):
$date = strtotime('+9 hours', (int)$db_time);
$timeUntilEvent = $date - time();
Now $timeUntilEvent contains the amount of seconds until the event. In JavaScript add that number to the timer:
var end_date = new Date();
end_date.setTime( end_date.getTime() + <?php echo $timeUntilEvent; ?> * 1000 );
Now the timer will fire at the correct time regardless of what time the user's clock is set to.
var end_date = new Date((<?php echo $end; ?>+32400)*1000);
end_date = end_date + ((3600*1000)*9);
mktime returns seconds, so you simply add the desired amount of seconds
using the end_date created with php, add this line:
end_date+=9*60*60
Call this before your countdown:
end_date = end_date.setTime((end_date + (9 * 3600)) * 1000).toGMTString();
EDIT: I removed the get_time() and the "* 1000" as end_date is already a UNIX timestamp.
EDIT2: Apparently, timestamps in js are in milliseconds so we also have to multiply the PHP timestamp (which is in seconds).

Converting string into Date() in JavaScript

How do I convert this timestamp from php into a javascript Date() object?
This is how I grab the time:
$timestart = time();
and I parse this to a javascript function and I want to convert it into a JavaScript date object.
help, all this date stuff confuses me quite a bit.
thanks,
If val contains your PHP value which is
the current time measured in the number of seconds since the Unix Epoch
then you just need this:
var timestart = new Date(val * 1000);
JavaScript uses the same base time as UNIX systems (midnight on 01/01/1970) but measured in milliseconds rather than seconds.
Solution here :
Convert a Unix timestamp to time in JavaScript
Substring the parts of the timestamp you need to create the Date. Then initialise like so,
var d = new Date(year, month, date);
This is a cross browser implementation.

JavaScript readable date/time from PHP's time()

Is it possible to have JavaScript compute a timestamp returned from PHP's time() function and present it in a readable format such as "Sun, 18th April 2010 at 4:00 pm"?
Use the Date object to do that:
new Date(<?php echo time(); ?>*1000)
You need to multiply the Unix timestamp by 1000 becuase Date expects the timestamp to be in milliseconds.
And to format the date, you can use this Date.format method (Date has none built in).
You're going to want to be really careful doing this stuff. When you take a server-side time value that's a traditional "number of seconds (or milliseconds) since the Epoch boundary" value, and then turn that into some sort of "Date" object, well a translation occurs into the time zone appropriate to the locale of the context.
The problem arises when you've got a server located in Chicago, and somebody in Hawaii using your site, say after a party — one of those "luau" affairs, no doubt, complete with roasted pig and grass-skirted dancing girls, a rare evening under warm tropical skies, exotic flowers scenting the ocean breezes — and it's late now. My goodness, it's almost midnight! Whatever will mother think when I write her about the party?
Our party-goer sits down at 11:30 PM to use your site. Now, of course, being considerably east of Hawaii, your server thinks it's 5:30AM, and the date is one day later than the date our party-goer will jot down in his quick note to Mom. So your server writes its time value into a web page as described in the answers here, and — correctly — the local Hawaii time shows up on the page in our party-goer's hotel room.
The problem is this: if that local time makes it back to your application from some form field, and your application treats it as local time in Chicago, then your site will get yesterday's date. Depending on your application that's either OK or it's not OK - the point is, you have to keep track of where a date (expressed in ordinary calendar notation) comes from vis-a-vis where the date is used.
You can of course have the opposite problem. That is, if your server always renders dates in its local time zone, then users elsewhere in the world will see confusing (apparently wrong) date and time values, so the interface has to make clear what those values mean. The issues become important when your site provides services involving schedules. If it's possible to schedule operations, it's important that the interface keeps things on the level so that "April 30th at 10:00PM" means either that date and time at the server or that date and time in the locale from which the schedule was arranged. Whichever it is, you have to be careful to keep things consistent.
Instead of a numeric unix timestamp you can also send a textual representation of the date that Date.parse() understands.
Maybe it's just my contribution to global warming but I think there are benefits in using a format that is a bit more human readable and contains the timezone info.
e.g.
<?php
// I have "decided" America/Los_Angeles fits most of my audience
date_default_timezone_set('America/Los_Angeles');
$now = time();
$yesterday = strtotime('yesterday', $now);
// March 27, 1976 08:00:00 tz:America/Los_Angeles
$someotherdate = mktime(8, 0, 0, 3, 27, 1976)
?><html>
<head><title>...</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function foo() {
$('.datetime').each( function() {
var t = $(this).text();
t = new Date(Date.parse(t)).toLocaleString();
$(this).text(t);
});
}
</script>
</head>
<body>
<div><span class="datetime"><?php echo date(DateTime::RSS, $now); ?></span></div>
<div><span class="datetime"><?php echo date(DateTime::RSS, $yesterday); ?></span></div>
<div><span class="datetime"><?php echo date(DateTime::RSS, $someotherdate); ?></span></div>
<button onclick="foo()">to local time</button>
</body>
</html>
This prints
Sat, 17 Apr 2010 04:40:15 -0700
Fri, 16 Apr 2010 00:00:00 -0700
Sat, 27 Mar 1976 08:00:00 -0800
in my browser and (since my local timezone is Europe/Berlin, CET, UTC+1/2) after hitting the to local time button
Samstag, 17. April 2010 13:40:15
Freitag, 16. April 2010 09:00:00
Samstag, 27. März 1976 17:00:00
It's now 2013, and as more and more people switch from processing SQL results on PHP side to passing results in JSON and processing on client side, I think moment.js deserves some attention of its own for offering easy replacements to PHP's strtotime() and date() functions in Javascript, plus some more.
Just include:
<script src="SCRIPT_DIR/moment.min.js" type="text/javascript"></script>
Then it's as easy as:
// Simulates ajax response
var data = { someDate: "2023-08-23 11:52:39" }
// .unix() converts to Unix timestamp: 1692816759
moment(data.someDate).unix();
// Displaying it in a readable format
// Aug 23, 11:52 AM
moment("2023-08-23 11:52:39").format('MMM D, hh:mm A');
// Now
moment();
// Support for manipulation and chaining
moment().add('days', 7).subtract('months', 1).hours(15).minutes(0).seconds(0);
You can get the 5.5kb js file here:
http://momentjs.com/
More docs here:
http://momentjs.com/docs/

Categories