PHP's gmmktime in JavaScript

How to use

You you can install via yarn add locutus and require this function via const gmmktime = require('locutus/php/datetime/gmmktime').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1gmmktime(14, 10, 2, 2, 1, 2008)1201875002
2gmmktime(0, 0, -1, 1, 1, 1970)-1

Here’s what our current JavaScript equivalent to PHP's gmmktime looks like.

module.exports = function gmmktime() {
// discuss at: https://locutus.io/php/gmmktime/
// original by: Brett Zamir (https://brett-zamir.me)
// original by: 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

const d = new Date()
const r = arguments
let i = 0
const 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]]()
// +1 to fix JS months.
r[i] += i === 3
} 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])

const time = d.getTime()

// 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 ((time / 1e3) >> 0) - (time < 0)
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP datetime functions


Star