• 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->ID,'video',true)); ?> ?v=2&alt=jsonc',function(data,status,xhr){
$("#yt_time-<?php echo get_the_ID(); ?>").html(data.data.duration);
$("#yt_views-<?php echo get_the_ID(); ?>").html(data.data.viewCount);
});
});
</script>
<span><div class="yt">Duration: </div><div id="yt_time-<?php echo get_the_ID(); ?>" class="yt"></div><div class="yt"> | </div><div class="yt">Views: </div><div id="yt_views-<?php echo get_the_ID(); ?>"class="yt"></div></span>
</a>
				</li>
			<?php endwhile;wp_reset_postdata();?>
	</ul><!-- #related-videos -->
</div><!-- #sidebar -->

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

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

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-<?php echo get_the_ID(); ?>").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-<?php echo get_the_ID(); ?>").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-<?php echo get_the_ID(); ?>").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('data is a ' + typeof data); data.data && console.log('data.data is a ' + typeof data.data); data.data.viewCount && console.log('data.data.viewCount is a ' + 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-<?php echo get_the_ID(); ?>").html( new TimeFormatter( data.data.duration ).in_seconds() );

or

var video_duration = new TimeFormatter( data.data.duration );
$("#yt_time-<?php echo get_the_ID(); ?>").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() );
}




<div id="yt_time"></div>
<div id="yt_views"></div>

  • 0

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

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

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

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

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 < 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 && component == 0){
            continue;
        }

        timeComponents.push(component);
    }

    //Pad each component (2 -> 02)
    for(var i = 0; i < 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

<?php

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

	$result = array();
	if($duration >= 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

PHP version

<?php

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

	$result = array();
	if($duration >= 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

    • Oh man, but what if I have the PS3 version?
    • Floorp 12.15.0 by Razvan Serea Floorp is a cutting-edge web browser that combines the trusted foundation of Mozilla's Firefox with a unique Japanese perspective, offering users an exceptional online experience. This open-source browser prioritizes privacy, customization, and security. Floorp is transparent, with no user tracking or data sharing, and it's completely open source. With a strict no-tracking policy and full transparency, your personal information remains private. As an open-source project, Floorp not only shares its source code but also its build environment, inviting users to contribute and build their unique versions. The regular updates, based on Firefox ESR, ensure that you always have the latest features and security enhancements. Floorp key features: Strong Tracking Protection: Floorp offers robust tracking protection, safeguarding users from malicious tracking and fingerprinting on the web. Flexible Layout: Customize Floorp's layout to your heart's content, including moving the tab bar, hiding the title bar, and more for a personalized browsing experience. Switchable Design: Choose from five distinct designs for the Floorp interface, and even switch between OS-specific designs for a unique look Regular Updates: Based on Firefox ESR, Floorp receives updates every four weeks, ensuring up-to-date security even before Firefox's releases. No User Tracking: Floorp prioritizes user privacy by abstaining from collecting personal information, tracking users, or selling user data, with no affiliations with advertising companies. Completely Open Source: The full source code for Floorp is open to the public, allowing transparency and enabling anyone to explore and build their own version. Dual Sidebar: Floorp features a versatile built-in sidebar for webpanels and browsing tools, making it perfect for multitasking and quick access to bookmarks, history, and websites. Flexible Toolbar & Tab Bar: Customize your browser with Tree Style Tabs, vertical tabs, and bookmark bar modifications, catering to both beginners and experts in customization. User-Centric Web Experience: Floorp prioritizes user privacy and collaboratively blocks harmful trackers. Floorp 12.15.0 changelog: Refine appearance of Start top sites and Hub sidebar by @CutterKnife in #2435 Improvement command pallete by @Walkmana-25 in #2429 Fix gesture command by @Walkmana-25 in #2425 Add Mac OS formatting for modifier keys in shortcut editor by @Walkmana-25 in #2424 refactor: bridge as little by @nyanrus in #2416 fix(pwa): follow Firefox 150 ShellService API changes (Bug 1985098) by @Ryosuke-Asano in #2409 feat(notes): Desktop向けThree-Way Merge Sync実装 by @Ryosuke-Asano in #2402 fix(pages-settings): resolve Invalid Hook Call error in SortableContext by @Ryosuke-Asano in #2350 README: fix signpath avatar url by @CutterKnife in #2453 Enhance command palette with new actions by @Walkmana-25 in #2449 feat(split-view): implement tab drop functionality with overlay and new window zone by @Ryosuke-Asano in #2445 fix: restore 'Hide Interface', 'Toggle Navigation Panel', and 'Rest Mode' keyboard shortcuts by @Ryosuke-Asano in #2458 fix: prevent unified extensions panel from closing on bottom navbar (#2079) by @Ryosuke-Asano in #2462 fix: prevent workspace system from overriding SessionStore tab selection on startup by @Ryosuke-Asano in #2461 fix: prevent multi-row tabs from disappearing when sidebar opens website by @Ryosuke-Asano in #2460 fix: prevent private container tab from saving first page to history by @Ryosuke-Asano in #2459 fix: prevent browser close when container tab is the only tab open by @Ryosuke-Asano in #2465 Resolve conflicts for #2467: Add split-view mouse gesture commands by @Ryosuke-Asano in #2472 fix(os-server): auto-generate auth token on enable by @Ryosuke-Asano in #2471 fix(settings): change broken link to Floorp Docs by @regularentropy in #2477 Enhanced search functionality in the command palette — now supports English keywords, Japanese morphological analysis, and hiragana search by @Walkmana-25 in #2470 fix(patches): align Gecko patches with Linux CI runtime by @Ryosuke-Asano in #2482 feat(pwa): add Firefox Container support for PWA apps by @Ryosuke-Asano in #2443 fix(statusbar): add event listener for buttons in status bar by @greeeen-dev in #2484 Download: Floorp 64-bit | 95.0 MB (Open Source) Links: Floorp Website | Github Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Google Gemini co-lead Noam Shazeer is leaving for OpenAI by Pradeep Viswanathan Noam Shazeer is best known as one of the co-authors of the 2017 “Attention Is All You Need” paper, which introduced the Transformer architecture that now powers most large language models. He also worked on several major Google AI projects, including LaMDA, before leaving the company in 2021 to co-found Character.AI. He also authored the Sparsely-gated Mixture of Experts (2016) paper, which is popular among the AI community. After falling behind OpenAI and Anthropic a couple of years ago, Google brought Shazeer back in 2024 as part of a major deal with Character.AI. Through this deal, along with Noam, several other researchers returned to Google DeepMind. More recently, he was a vice president of engineering at Google and a technical co-lead for Gemini. Today, Noam Shazeer announced on X that he is leaving Google and joining OpenAI. In his post, Shazeer said it was a difficult decision to move on, adding that he was proud of the Google team and what it had built together. OpenAI CEO Sam Altman welcomed the move with a post of his own, saying Shazeer was one of the people he had most wanted to work with since OpenAI’s early days. Google has made strong progress with Gemini over the past year, closing the gap with OpenAI in several areas. But losing Noam Shazeer is a major talent setback for them, especially after bringing him back less than two years ago by spending a fortune. For OpenAI, the hire adds one of the industry’s most experienced language model researchers to a team that is already pushing ahead with ChatGPT, Codex, and its next generation of frontier models.
    • I'm lost too... what did you mean by your first comment then?
  • Recent Achievements

    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
    • One Month Later
      eurospharma62 earned a badge
      One Month Later
    • Week One Done
      With What earned a badge
      Week One Done
    • Week One Done
      Harris Gilbert earned a badge
      Week One Done
    • One Month Later
      Vincian earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      541
    2. 2
      +Edouard
      171
    3. 3
      PsYcHoKiLLa
      85
    4. 4
      ATLien_0
      64
    5. 5
      neufuse
      64
  • Tell a friend

    Love Neowin? Tell a friend!