UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

96 lines (79 loc) 2.83 kB
--- layout: page title: "JavaScript gmmktime function" comments: true sharing: true footer: true alias: - /functions/view/gmmktime:779 - /functions/view/gmmktime - /functions/view/779 - /functions/gmmktime:779 - /functions/779 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's gmmktime {% codeblock datetime/gmmktime.js lang:js https://raw.github.com/kvz/phpjs/master/functions/datetime/gmmktime.js raw on github %} function gmmktime () { // From: http://phpjs.org/functions // + original by: Brett Zamir (http://brett-zamir.me) // + derived from: mktime // * example 1: gmmktime(14, 10, 2, 2, 1, 2008); // * returns 1: 1201875002 // * example 2: gmmktime(0, 0, -1, 1, 1, 1970); // * returns 2: -1 var d = new Date(), r = arguments, i = 0, e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear']; for (i = 0; i < e.length; i++) { if (typeof r[i] === 'undefined') { r[i] = d['getUTC' + e[i]](); r[i] += (i === 3); // +1 to fix JS months. } else { r[i] = parseInt(r[i], 10); if (isNaN(r[i])) { return false; } } } // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000. r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0); // Set year, month (-1 to fix JS months), and date. // !This must come before the call to setHours! d.setUTCFullYear(r[5], r[3] - 1, r[4]); // Set hours, minutes, and seconds. d.setUTCHours(r[0], r[1], r[2]); // Divide milliseconds by 1000 to return seconds and drop decimal. // Add 1 second if negative or it'll be off from PHP by 1 second. return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0); } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/datetime/gmmktime.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/datetime/gmmktime.js) ### Example 1 This code {% codeblock lang:js example %} gmmktime(14, 10, 2, 2, 1, 2008); {% endcodeblock %} Should return {% codeblock lang:js returns %} 1201875002 {% endcodeblock %} ### Example 2 This code {% codeblock lang:js example %} gmmktime(0, 0, -1, 1, 1, 1970); {% endcodeblock %} Should return {% codeblock lang:js returns %} -1 {% endcodeblock %} ### Other PHP functions in the datetime extension {% render_partial _includes/custom/datetime.html %}