• 0

Convert Video Duration Number to Time with PHP or jQuery


Question

I'm loading the YouTube API by jQuery + JSON to get the video info of it's views and duration.

The duration number for example is 210 sample, but in actually time, it's 3:30. :)

The problem is, I'm not sure how to come by to converting the numbers to actually time, not even with PHP's strtotime since I believe jQuery would load too late for that. (Or I don't know at all.) :p

<div id="sidebar">
<h3>Related Videos</h3>
	<ul id="related-videos">
<?php $the_query = new WP_Query( array( 'posts_per_page' => '5', 'post_format' => 'post-format-video','category_name' => 'hip-hop') );
			while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
			 <li>
<a href="<?php the_permalink();?>">
<div class="side-thumb"><?php the_post_thumbnail('small'); ?></div>
				 <?php the_title(); ?><br />
						<script type="text/javascript">
$(document).ready(function () {
$.getJSON('http://gdata.youtube.com/feeds/api/videos/<?php echo getYouTubeIdFromURL(get_post_meta($post-&gt;ID,'video',true)); ?&gt; ?v=2&amp;alt=jsonc',function(data,status,xhr){
$("#yt_time-&lt;?php echo get_the_ID(); ?&gt;").html(data.data.duration);
$("#yt_views-&lt;?php echo get_the_ID(); ?&gt;").html(data.data.viewCount);
});
});
&lt;/script&gt;
&lt;span&gt;&lt;div class="yt"&gt;Duration: &lt;/div&gt;&lt;div id="yt_time-&lt;?php echo get_the_ID(); ?&gt;" class="yt"&gt;&lt;/div&gt;&lt;div class="yt"&gt; | &lt;/div&gt;&lt;div class="yt"&gt;Views: &lt;/div&gt;&lt;div id="yt_views-&lt;?php echo get_the_ID(); ?&gt;"class="yt"&gt;&lt;/div&gt;&lt;/span&gt;
&lt;/a&gt;
				&lt;/li&gt;
			&lt;?php endwhile;wp_reset_postdata();?&gt;
	&lt;/ul&gt;&lt;!-- #related-videos --&gt;
&lt;/div&gt;&lt;!-- #sidebar --&gt;

I think this is the solution, but I don't exactly know how to use it. This code is from Stack Overflow.

&lt;?php date('Y-m-d H:i:s', strtotime(sprintf('- %d second', round($speed * 60)))); ?&gt;

Here's a screenshot of what I'm working on. Check out the "Related Videos" on the bottom right.

post-388684-0-44370700-1349869128_thumb.

19 answers to this question

Recommended Posts

  • 0

Something along these lines...

var seconds = 0,
    multiplier = 1,
    time = '3:30';

time = time.split(':');
while (time.length)
{
  seconds += multiplier * parseInt( time.pop() );
  multiplier *= 60;
}

Or a slight variation to cut out a line

var seconds = 0,
    multiplier = 1/60,
    time = '3:30';

time = time.split(':');
while (time.length)
{
  seconds += (multiplier *= 60) * parseInt( time.pop() );
}

  • 0

Sweet! But how do I implement it with this since it appends into a DIV? This is actually in a loop on WordPress, so it won't be a specific time.

$("#yt_views-&lt;?php echo get_the_ID(); ?&gt;").html(data.data.viewCount);

  • 0

Put this somewhere in the document, along with the rest of your script:

function TimeFormatter (time) {
  this.base_time = time;
}

TimeFormatter.prototype = {

  in_seconds: function () {
	var seconds = 0,
		multiplier = 1/60;

	time = this.base_time.split(':');
	while (time.length)
	{
	  seconds += (multiplier *= 60) * parseInt( time.pop() );
	}

	return seconds;
  }

};

Then you can either use this to just print out the seconds directly

$("#yt_views-&lt;?php echo get_the_ID(); ?&gt;").html( new TimeFormatter( data.data.viewCount ).in_seconds() );

or create an instance of the object for use elsewhere:

var video_duration = new TimeFormatter( data.data.viewCount );
$("#yt_views-&lt;?php echo get_the_ID(); ?&gt;").html( video_duration.in_seconds() );

  • 0

The Console says

Uncaught TypeError: Object 1372224 has no method 'split' illigion.js:18

Uncaught TypeError: Object 19194 has no method 'split' illigion.js:18

Uncaught TypeError: Object 5789858 has no method 'split' illigion.js:18

It voids both duration & view no matter which I use or where I put it, as is.

  • 0

In that case, `data.data.viewCount` isn't a string - can you post what the contents of that are? Drop this into the script:

console.log('dataa ' + typeof data); data.data &amp;&amp; console.log('data.dataa ' + typeof data.data); data.data.viewCount &amp;&amp; console.log('data.data.viewCounta ' + typeof data.data.viewCount + ', and its value is: ' + data.data.viewCount);

  • 0

"data is a object"

"data data is a object"

"data data viewCount is a number, and its value is: 137224"

Oh, wait! I don't think viewCount was what I was thinking about. Back to duration, the error is being caused from that!

.html( new TimeFormatter( data.data.viewCount ).in_seconds() );

  • 0

Ahaha, I'm not sure why I latched on to `.viewCount` there - that's my bad. Change it to `.duration` (ie. put it on the line above, which has duration) and that should work.

$("#yt_time-&lt;?php echo get_the_ID(); ?&gt;").html( new TimeFormatter( data.data.duration ).in_seconds() );

or

var video_duration = new TimeFormatter( data.data.duration );
$("#yt_time-&lt;?php echo get_the_ID(); ?&gt;").html( video_duration.in_seconds() );

  • 0

Haha, still no bueno. :p

Here, try it without PHP and using a direct url on YouTube! :D

$(document).ready(function () {
function TimeFormatter (time) {
this.base_time = time;
}

TimeFormatter.prototype = {

in_seconds: function () {
var seconds = 0,
multiplier = 1/60;

time = this.base_time.split(':');
while (time.length)
{
seconds += (multiplier *= 60) * parseInt( time.pop() );
}

return seconds;
}

};

$.getJSON('http://gdata.youtube.com/feeds/api/videos/bCQKlK7WhTM?v=2&alt=jsonc',function(data,status,xhr/ new code
var video_duration = new TimeFormatter( data.data.duration );
$("#yt_time").html( video_duration.in_seconds() );
// end new code
$("#yt_views").html(data.data.viewCount);
});
});

var seconds = 210,
multiplier = 1/60,
time = '3:30';

time = time.split(':');
while (time.length)
{
seconds += (multiplier *= 60) * parseInt( time.pop() );
}




&lt;div id="yt_time"&gt;&lt;/div&gt;
&lt;div id="yt_views"&gt;&lt;/div&gt;

  • 0
  On 10/10/2012 at 15:22, Heartripper said:

Sorry but you want to convert 210 to 3:30 or the other way around?

210 to 3:30

Check out the API data and find "duration"

http://gdata.youtube.com/feeds/api/videos/bCQKlK7WhTM?v=2&alt=jsonc

  • 0
  On 10/10/2012 at 15:24, MrXXIV said:

210 to 3:30

Check out the API data and find "duration"

http://gdata.youtube.com/feeds/api/videos/bCQKlK7WhTM?v=2&alt=jsonc

Ok i van write you the code but atm i'm on my Phone :-(

  • 0
  On 10/10/2012 at 15:28, Heartripper said:

Ok i van write you the code but atm i'm on my Phone :-(

Take your time broski. :)

For the both of you. Here's where you can see and work it out! :D Everything's locked out but that page since I have it all in re-development.

http://illingspree.c...es-music-video/

  • 0
  On 10/10/2012 at 15:49, JoeC said:

O_o Apparently I read it totally wrong, my code converts the other way - 3:30 to 210. If this is still waiting for an answer when I get home, I'll sit down and write it.

Haha it's okay. Yea, I'm still in a confusion on it here. I'm definitely going to need some help on that and maybe writing commas on the view count to make it a little more readable.

  • 0
  On 10/10/2012 at 15:54, MrXXIV said:

Haha it's okay. Yea, I'm still in a confusion on it here. I'm definitely going to need some help on that and maybe writing commas on the view count to make it a little more readable.

here it is:

function formatDuration(duration){
    //We only accept numbers
    if(typeof duration != "number"){
        return;
    }

    var pad = function(n){return n &lt; 10 ? "0" + n : "" + n},
        timeComponents = [], multiplier = 3600;

    //Compute the value of each component (hours, minute, seconds)
    for(; multiplier != 0; multiplier = parseInt(multiplier / 60)){
        var component = parseInt(duration / multiplier);
        duration %= multiplier;

        //If hours equal to 0, do not add them.
        if(multiplier == 3600 &amp;&amp; component == 0){
            continue;
        }

        timeComponents.push(component);
    }

    //Pad each component (2 -&gt; 02)
    for(var i = 0; i &lt; timeComponents.length; i++){
        var padded = pad(timeComponents[i]);
        timeComponents[i] = padded;
    }

    return timeComponents.join(":");
}

tell me if you want some tweaks. It converts seconds to hours:minutes:seconds format, e.g. 51823 -> 14:23:43

  • 0

PHP version

&lt;?php

function formatDuration($duration){
	$duration = intval($duration);
	if(!$duration) return;

	$result = array();
	if($duration &gt;= 3600) {
		// Hours
		$result[] = str_pad(floor($duration / 3600),2,"0",STR_PAD_LEFT);
		$duration = $duration % 3600;
	}
	$result[] = str_pad(floor($duration / 60),2,"0",STR_PAD_LEFT);
	$result[] = str_pad($duration % 60,2,"0",STR_PAD_LEFT);

	return implode($result, ':');
}

  • 0
  On 11/10/2012 at 21:13, Tjcool007 said:

PHP version

&lt;?php

function formatDuration($duration){
	$duration = intval($duration);
	if(!$duration) return;

	$result = array();
	if($duration &gt;= 3600) {
		// Hours
		$result[] = str_pad(floor($duration / 3600),2,"0",STR_PAD_LEFT);
		$duration = $duration % 3600;
	}
	$result[] = str_pad(floor($duration / 60),2,"0",STR_PAD_LEFT);
	$result[] = str_pad($duration % 60,2,"0",STR_PAD_LEFT);

	return implode($result, ':');
}

Won't that only work if I had a PHP version of the jQuery JSON function?

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft 365 Word gets SharePoint eSignature, now you can ditch third-party signing tools by Paul Hill Microsoft has just announced that it will be rolling out an extremely convenient feature for Microsoft 365 customers who use Word throughout this year. The Redmond giant said that you’ll now be able to use SharePoint’s native eSignature service directly in Microsoft Word. The new feature allows customers to request electronic signatures without converting the documents to a PDF or leaving the Word interface, significantly speeding up workflows. Microsoft’s integration of eSignatures also allows you to create eSignature templates which will speed up document approvals, eliminate physical signing steps, and help with compliance and security in the Microsoft 365 environment. This change has the potential to significantly improve the quality-of-life for those in work finding themselves adding lots of signatures to documents as they will no longer have to export PDFs from Word and apply the signature outside of Word. It’s also key to point out that this feature is integrated natively and is not an extension. The move is quite clever from Microsoft, if businesses were using third-party tools to sign their documents, they would no longer need to use these as it’s easier to do it in Word. Not only does it reduce reliance on other tools, it also makes Microsoft’s products more competitive against other office suites such as Google Workspace. Streamlined, secure, and compliant The new eSignature feature is tightly integrated into Word. It lets you insert signature fields seamlessly into documents and request other people’s signatures, all while remaining in Word. The eSignature feature can be accessed in Word by going to the Insert ribbon. When you send a signature request to someone from Word, the recipient will get an automatically generated PDF copy of the Word document to sign. The signed PDF will then be kept in the same SharePoint location as the original Word file. To ensure end-to-end security and compliance, the document never leaves the Microsoft 365 trust boundary. For anyone with a repetitive signing process, this integration allows you to turn Word documents into eSignature templates so they can be reused. Another feature that Microsoft has built in is audit trail and notifications. Both the senders and signers will get email notifications throughout the entire signing process. Additionally, you can view the activity history (audit trail) in the signed PDF to check who signed it and when. Finally, Microsoft said that administrators will be able to control how the feature is used in Word throughout the organization. They can decide to enable it for specific users via an Office group policy or limit it to particular SharePoint sites. The company said that SharePoint eSignature also lets admins log activities in the Purview Audit log. A key security measure included by Microsoft, which was mentioned above, was the Microsoft 365 trust boundary. By keeping documents in this boundary, Microsoft ensures that all organizations can use this feature without worry. The inclusion of automatic PDF creation is all a huge benefit to users as it will cut out the step of manual PDF creation. While creating a PDF isn’t complicated, it can be time consuming. The eSignature feature looks like a win-win-win for organizations that rely on digital signatures. Not only does it speed things along and remain secure, but it’s also packed with features like tracking, making it really useful and comprehensive. When and how your organization gets it SharePoint eSignature has started rolling out to Word on the M365 Beta and Current Channels in the United States, Canada, the United Kingdom, Europe, and Australia-Pacific. This phase of the rollout is expected to be completed by early July. People in the rest of the world will also be gaining this time-saving feature but it will not reach everyone right away, though Microsoft promises to reach everybody by the end of the year. To use the feature, it will need to be enabled by administrators. If you’re an admin who needs to enable this, just go to the M365 Admin Center and enable SharePoint eSignature, ensuring the Word checkbox is selected. Once the service is enabled, apply the “Allow the use of SharePoint eSignature for Microsoft Word” policy. The policy can be enabled via Intune, Group Policy manager, or the Cloud Policy service for Microsoft 365 Assuming the admins have given permission to use the feature, users will be able to access SharePoint eSignatures on Word Desktop using the Microsoft 365 Current Channel or Beta Channel. The main caveats include that the rollout is phased, so you might not get it right away, and it requires IT admins to enable the feature - in which case, it may never get enabled at all. Overall, this feature stands to benefit users who sign documents a lot as it can save huge amounts of time cumulatively. It’s also good for Microsoft who increase organizations’ dependence on Word.
    • It's always good to have an option to secure your stuff to another medium. I did that with DVD/CD collection, and run my own media server now. It's more convenient that way and no need for separate players anymore.
    • Google Search AI Mode gets support for data visualization and custom charts by Aditya Tiwari Google announced it is rolling out support for data visualizations and graphs for finance-related queries in Google Search's AI Mode. Introduced last month at the Google I/O 2025 keynote, the feature lets you analyze complex datasets and create custom charts simply using natural language prompts. The updated AI Mode lets you compare and analyze information over a specific period, Google explained. It generates interactive graphs and provides a comprehensive explanation for your questions. AI Mode utilizes Gemini's multimodal capabilities and multi-step reasoning approach to comprehend the question's intent while accessing historical and real-time information relevant to the question. For instance, instead of manually researching individual companies and their stock prices, you can use AI Mode to compare the stock performance of different companies for a specific year. Once the graph is generated, you can choose the desired time period using the mouse cursor and ask follow-up questions based on the data presented. These new data visualizations for finance queries are available to users who have enabled the AI Mode experiment in Labs. AI Mode was introduced earlier this year as an experimental feature in the US. The feature is an upgraded version of AI Overviews, and Google closely worked with AI power users through the initial development process. It uses the “query fan-out” technique to perform multiple related searches across subtopics and different data sources, then combines them to come up with a comprehensive response. Google updated AI Mode last month to use a custom version of the latest Gemini 2.5 model. It added several new features, including Deep Search, live capabilities, agentic capabilities of Project Mariner, a new shopping experience, and the ability to add personal context by linking Google apps. The search giant is planning to turn AI Mode into its bread and butter. It has begun testing ads for the feature, which will appear below and be integrated into AI Mode responses where relevant.
    • Guys, you should find another way to promote your deals... It's the third article in the last months that promote this deal for an upgrade from 10. Considering that upgrade from 10 to 11 is free it's a total non-sense.
    • Store should be a shrine of useful applications, vetted and verified. Easily sorted by publisher. Windows should start with not much installed and have things as options in the store. Not the wild west mess that it is. You could delete 95%+ of the crap on there and no one would notice. They need to add a better UI to the updates, it's awful right now.
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      431
    2. 2
      +FloatingFatMan
      239
    3. 3
      snowy owl
      212
    4. 4
      ATLien_0
      211
    5. 5
      Xenon
      157
  • Tell a friend

    Love Neowin? Tell a friend!