JavaScript mktime
Get UNIX timestamp for a date
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 42 43 44 4546 47 48 49 5051 52 53 54 5556 57 58 59 6061 62 63 64 6566 67 68 69 70 | function mktime() { // Get UNIX timestamp for a date // // version: 1008.1718 // discuss at: http://phpjs.org/functions/mktime // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: baris ozdil // + input by: gabriel paderni // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: FGFEmperor // + input by: Yannoo // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: jakes // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Marc Palau // + improved by: Brett Zamir (http://brett-zamir.me) // + input by: 3D-GRAF // + bugfixed by: Brett Zamir (http://brett-zamir.me) // + input by: Chris // + revised by: Theriault // % note 1: The return values of the following examples are // % note 1: received only if your system's timezone is UTC. // * example 1: mktime(14, 10, 2, 2, 1, 2008); // * returns 1: 1201875002 // * example 2: mktime(0, 0, 0, 0, 1, 2008); // * returns 2: 1196467200 // * example 3: make = mktime(); // * example 3: td = new Date(); // * example 3: real = Math.floor(td.getTime() / 1000); // * example 3: diff = (real - make); // * results 3: diff < 5 // * example 4: mktime(0, 0, 0, 13, 1, 1997) // * returns 4: 883612800 // * example 5: mktime(0, 0, 0, 1, 1, 1998) // * returns 5: 883612800 // * example 6: mktime(0, 0, 0, 1, 1, 98) // * returns 6: 883612800 // * example 7: mktime(23, 59, 59, 13, 0, 2010) // * returns 7: 1293839999 // * example 8: mktime(0, 0, -1, 1, 1, 1970) // * returns 8: -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['get' + 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.setFullYear(r[5], r[3] - 1, r[4]); // Set hours, minutes, and seconds. d.setHours(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); } |
Examples
» Example 1
Running
1 | mktime(14, 10, 2, 2, 1, 2008); |
Should return
1 | 1201875002 |
» Example 2
Running
1 | mktime(0, 0, 0, 0, 1, 2008); |
Should return
1 | 1196467200 |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have mktime goodness in JavaScript.
@Chris: Thank you for finding this bug. The function has been updated to fix this bug as well as others. (http://github.com/kvz/phpjs/raw/master/functions/datetime/mktime.js)
PHP: mktime(23,59,59,13,0,2010) => 1293857999
PHPJS: mktime(23,59,59,13,0,2010) => 1325393999
Looks like it doesn't like the '13' month with the '0' day which should be the last day of the previous month.
_.mktime = function()
{
var a = date();
arguments.length > 1 && a.setHours.apply( a, arguments );
arguments.length > 3 && a.setFullYear( arguments[5] == un ? a.getFullYear() : arguments[5], arguments[3] == un ? a.getMonth() : arguments[3] - 1, arguments[4] == un ? a.getDate() : arguments[4] );
return _.floor( a.getTime() / 1000 );
},
我写的JS类 下载地址 有爱好的可以探讨
http://bgscript.com/jscore/script/core.js
@swyong: Are you using the latest version of the function? If yes, what errors are you getting? (e.g., if using Firefox, what does it say in Tools->Error Console when you run the function?) I'm not getting any errors with the code you gave...
The reason no arguments appear is because the automatically-built "arguments" object (available in JavaScript, like func_get_args() in PHP if you know what that is) is used here to get that information.
i cannot return the UNIX value which i put the argument. but it's working without the argument.(return today UNIX)
mktime(0,0,0,10,2,2009); this is argument i put.
and i notice that this function dun have any arguments needed. function mktime () {....}
im newbie, please help.
@3D-GRAF : Thanks for the report. Since the date today (whether the 29th or 30th) is an impossible day for February, our function was mistakenly moving the month up to March. Fixed in SVN.
Please note though that while we have date_default_timezone_set() implemented (it uses this.php_js.default_timezone to store the current timezone), mktime (and no doubt a number of others) do not use the information yet.
So, it will currently just work against the current locale in the user's JavaScript--and you can't directly control the timezone via JavaScript. So, we have to fix mktime at some point to check our own this.php_js.default_timezone and adjust the time and possibly date accordingly in case someone wishes to control the timezone via JS (as opposed to letting the user's locale determine that).
Found bug:
mktime(0, 0, 0, 2, 23, 2009);
Results:
JS: 1237755600
PHP: 1235336400
Need a solution, help.
Are you in a different time zone than your server? JavaScript can only use the user's default timezone unless we were to program the function to work with date_default_timezone_set(), as we should, but in that case you'd still need to call that extra function... Any patches are welcome...
Hello mans!
I executed mktime(0,0,0,7,1,1975) sintax under both of javascript and php, and I have got not equal results.
The js produced this: 173397600
The php produced this: 173401200
This is a bug!
Have a nice day!
@ Marc Palau: Maybe it's because we're in different timezones, but your function fails the second & 3rd test. So, sorry but I cannot replace the current implementation just yet.
And:
[CODE="Javascript"]
no = parseInt(argv[i]*1);
[/CODE]
already multiplies by one, btw.
Two comments on one:
I'm not agree with tath mod. man, you are not filtering the arguments.
Definetively this is all wrong (sorry man)
I have rewrited the function, please take a test and tell me if I'm OK:
[CODE="Javascript"]function mktime() {
//agree here
var d = new Date(), argv = arguments;
var cH=argv[0]!=undefined?argv[0]*1:d.getHours(),//hours
ci=argv[1]!=undefined?argv[1]*1:d.getMinutes(),//minutes
cs=argv[2]!=undefined?argv[2]*1:d.getSeconds(),//second
cn=argv[3]!=undefined?(argv[3]*1)-1:d.getMonth(),//month
cj=argv[4]!=undefined?argv[4]*1:d.getDate(),//day
cY=argv[5]!=undefined?argv[5]*1:d.getYear()+1900;//year
d.setHours(cH,ci,cs); d.setDate(cj); d.setMonth(cn); d.setYear(cY);
return Math.floor(d.getTime()/1000);
}[/CODE]
To test I have used this code:
[CODE="Javascript"]function test(){
document.body.appendChild(div=document.createElement("div"));
var w=function(v){
div.innerHTML+=v+"<br>";
}
w("xx:xx:xx xx/xx/xxxx: "+mktime());
w("10:xx:xx xx/xx/xxxx: "+mktime(10));
w("10:10:xx xx/xx/xxxx: "+mktime(10,10,10));
w("10:10:10 10/xx/xxxx: "+mktime(10,10,10,10));
w("10:10:00 10/10/xxxx: "+mktime(10,10,10,10,10));
w("10:10:10 10/10/2000: "+mktime(10,10,10,10,10,2000));
w("00:00:00 05/03/2008: "+mktime(0, 0, 0, '05', '03', '2008')+" [<?=mktime(0, 0, 0, '05', '03', '2008')?>]");
w("00:00:00 05/04/2008: "+mktime(0, 0, 0, '05', '04', '2008')+" [<?=mktime(0, 0, 0, '05', '04', '2008')?>]");
w("00:00:00 05/05/2008: "+mktime(0, 0, 0, '05', '05', '2008')+" [<?=mktime(0, 0, 0, '05', '05', '2008')?>]");
w("00:00:00 05/06/2008: "+mktime(0, 0, 0, '05', '06', '2008')+" [<?=mktime(0, 0, 0, '05', '06', '2008')?>]");
w("00:00:00 05/07/2008: "+mktime(0, 0, 0, '05', '07', '2008')+" [<?=mktime(0, 0, 0, '05', '07', '2008')?>]");
w("00:00:00 05/08/2008: "+mktime(0, 0, 0, '05', '08', '2008')+" [<?=mktime(0, 0, 0, '05', '08', '2008')?>]");
w("00:00:00 05/09/2008: "+mktime(0, 0, 0, '05', '09', '2008')+" [<?=mktime(0, 0, 0, '05', '09', '2008')?>]");
w("00:00:00 05/10/2008: "+mktime(0, 0, 0, '05', '10', '2008')+" [<?=mktime(0, 0, 0, '05', '10', '2008')?>]");
w("00:00:00 05/11/2008: "+mktime(0, 0, 0, '05', '11', '2008')+" [<?=mktime(0, 0, 0, '05', '11', '2008')?>]");
}[/CODE]
And a free tip:
parseInt('09') it's an octet, 9 don't exist, return false or 0; parseInt('08') will fail too
parseInt('05') return 5
parseInt('010') return 8
parseInt('011') return 9
var n='09'*1; work fine ;) //parseInt it's not necesary
Please, make the textarea bigger ;)
if you need something more, please send me an e-mail :) (I visit usually your project, but not every day)
good luck!
Marc
http://www.nbsp.es
@ Marc Palau: We still need that line for the other examples to work, but I think we got it right now. Agree? Thanks for helping us out Marc!
Kevin, the returned value by mktime on php without arguments (or with less arguments) is based on the current date, not [0,0,0,1,1,1972].
To solve, just delete this line:
[CODE="javascript"]d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);[/CODE]
Thanks!!
Marc
when iterating through a loop with negative values for month, on the transition to positive (zero month) php delivers expected values but js doesnt, ie:
[CODE="Javascript"]alert(mktime(0,0,0,0,1,2008) + " - " + date('d M Y', mktime(0,0,0,0,1,2008)));[/code]
[CODE="php"]echo mktime(0, 0, 0, 0, 1, 2008)." - ".date("d M Y", mktime(0, 0, 0, 0, 1, 2008));[/code]
js: 1201788000 - 01 Feb 2008
php: 1196427600 - 01 Dec 2007
@ Yanno: I have found the bug. It lays in using '09'. When using a number 9, the function worked normally. So I investigated further and it turns out that
[CODE="Javascript"]
parseInt('09') // returns 0 instead of 9
[/CODE]
Multiplying by 1 seems to work:
[CODE="Javascript"]
parseInt('09'*1) // returns 9 as it 'should'
[/CODE]
Thank you for all the info.
Well, this is my script :
[CODE="Javascript"]
function dateFr2timestamp(dateFr) {
var a_date = explode('/', dateFr); // array with {0:day; 1:month; 2:year)
return mktime(0,0,0,a_date[1],a_date[0],a_date[2]);
}
[/CODE]
dateFr is any date to french format (dd/mm/yyyy) --> '08/05/2008', '01/01/2008', '31/12/2008', ...
With dates '08/05/2008' and '09/05/2008', there are problems : wrong timestamp
@Kevin
I've test different date. Look results :
[CODE="Javascript"]
alert(mktime(0, 0, 0, '05', '03', '2008')); // 1209765600
alert(mktime(0, 0, 0, '05', '04', '2008')); // 1209852000
alert(mktime(0, 0, 0, '05', '05', '2008')); // 1209938400
alert(mktime(0, 0, 0, '05', '06', '2008')); // 1210024800
alert(mktime(0, 0, 0, '05', '07', '2008')); // 1210111200
alert(mktime(0, 0, 0, '05', '08', '2008')); // 1209592800 (it should be 1210197600)
alert(mktime(0, 0, 0, '05', '09', '2008')); // 1209592800 (it should be 1210284000)
alert(mktime(0, 0, 0, '05', '10', '2008')); // 1210370400
alert(mktime(0, 0, 0, '05', '11', '2008')); // 1210465800
[/CODE]
My timezone is Paris (GMT+1)
I've test different date. Look results :
[CODE="Javascript"]
alert(mktime(0, 0, 0, 5, 03, 2008)); // 1209765600
alert(mktime(0, 0, 0, 5, 04, 2008)); // 1209852000
alert(mktime(0, 0, 0, 5, 05, 2008)); // 1209938400
alert(mktime(0, 0, 0, 5, 06, 2008)); // 1210024800
alert(mktime(0, 0, 0, 5, 07, 2008)); // 1210111200
alert(mktime(0, 0, 0, 5, 08, 2008)); // 1209592800
alert(mktime(0, 0, 0, 5, 09, 2008)); // 1209592800
alert(mktime(0, 0, 0, 5, 10, 2008)); // 1210370400
alert(mktime(0, 0, 0, 5, 11, 2008)); // 1210465800
[/CODE]
@ Yannoo: What output are you getting? What should it be? Could this be related to the different timezones?
There are a probleme with :
[CODE="Javascript"]
mktime(0, 0, 0, 5, 8, 2008);
mktime(0, 0, 0, 5, 9, 2008);
[/CODE]
The timestamp is wrong !
@ Philip Peterson: If it's even possible to set the timezone for an entire page... I think you can only do this to a date object.
So maybe the right approach is to include a
[CODE="Javascript"]
+(date.getTimeZoneOffset() * 60 * 60);
[/CODE]
In the test to neutralize the end user's timezone?
@ Philip Peterson: Hi Philip. Running the tests in a predefined timezone seems to be a good solution. We should opt for UTC I think. Then adjust the 'result' comment to match the UTC outcome of mktime. Much better indeed!
Hmm, yeah, I figured that might be it, but does PHP do that? If not it might be a good idea to set the timezone to UTC/GMT/Something as a standard, or maybe including a config file to choose whether to leave it up to the user's computer or to set a standard?
Just so you know... this is six hours off in firefox, I think? :-/ In the php_tester example, at least... I'm not sure what's doing it, though...
OK, now setting a month to something greater than 11 would not increase the year...
My correction (also for hours, minutes and seconds...
[CODE="Javascript"]
var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
var dateManip = {
0: function(tt){ return d.setHours(tt); },
1: function(tt){ return d.setMinutes(tt); },
2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
4: function(tt){ return d.setDate(tt+mb); },
5: function(tt){ return d.setYear(tt+ma); }
};
[/CODE]
Basically I added 'ma' and 'mb' to the vars, and summed that on Years and Days... =)
OK, another update:
change
d.setYear(1970);
to
d.setYear(1972);
Why? Because this way Leap Years are gonna work.
Got It!
Add
[CODE="Javascript"]d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1970);[/CODE]
after
[CODE="Javascript"]var no, i = 0, d = new Date(), argv = arguments, argc = argv.length;[/CODE]
The catch here is that d = New Date(); sets d to the current date. What was happening is that today is the 31th, and I the function was setting the month to February, but the day was still the 31th, then it would set the month to March (since February has only 28/29 days). ;-)
I have no idea why, but this:
alert('PHP: <?= mktime(0,0,0,4,5,2009); ?>\nJS: '+mktime(0,0,0,4,5,2009));
returns this:
PHP: 1238900400
JS: 1241550694
Any idea why? That way, I should get 4/5/2009 for both, but I'm getting 5/5/2009 on the JS version...
@ gabriel paderni: The example won't reproduce:
http://kevin.vanzonneveld.net/test.php
But I've added the parseInt function. Does that solve the bug? Thanks gabriel!
If i'm not mistaken there's a bug when using strings as parameters:
here is the test I've made:
[CODE="Javascript"]
<script type="text/javascript">
function mktimetest(t_php,t_js){
document.write(t_php+'<br />'+t_js);
if(t_php!=t_js)document.write(' &lt;- Error');
document.write('<br /><br />');
}
mktimetest(<?php echo mktime('01','30','10','06','21','2008')?>,mktime('01','30','10','06','21','2008'));
mktimetest(<?php echo mktime('01','30','10','07','21','2008')?>,mktime('01','30','10','07','21','2008'));
mktimetest(<?php echo mktime('01','30','10','08','21','2008')?>,mktime('01','30','10','08','21','2008'));
mktimetest(<?php echo mktime('01','30','10','09','21','2008')?>,mktime('01','30','10','09','21','2008'));
mktimetest(<?php echo mktime('01','30','10','10','21','2008')?>,mktime('01','30','10','10','21','2008'));
mktimetest(<?php echo mktime('01','30','10','11','21','2008')?>,mktime('01','30','10','11','21','2008'));
</script>
[/CODE]
Strangely in the test this shows up only for August and September.
The solution may be to remove the leading zero when the parameter is a string.
(Tested with: Firefox and Internet explorer, same result.)
@ Michael White: Tried to reproduce the behavior, but wasn't able to:
http://kevin.vanzonneveld.net/test.php
The example appears to be incorrect for this function. I checked in a PHP script to verify this and to get the correct value.
The new example:
[CODE="Javascript"]
// * example 1: mktime( 14, 10, 2, 2, 1, 2008 );
// * returns 1: 1201893002
[/CODE]
@ baris ozdil: Thank your for your contribution, I've updated php.js and included you in the credits!
Hi Kevin,
Thanks a lot for this nice library.
Just a small correction in mktime. In javascript the setMonth the month values are 0 based indexed. I think it should be something like this:
[CODE="javascript"]
var dateManip = {
0: function(tt){ return d.setHours(tt); },
1: function(tt){ return d.setMinutes(tt); },
2: function(tt){ return d.setSeconds(tt); },
3: function(tt){ return d.setMonth(parseInt(tt)-1); },
4: function(tt){ return d.setDate(tt); },
5: function(tt){ return d.setYear(tt); }
};
[/CODE]
@ _argos: One thing: array_rand produces javascript errors when you feed it an object instead of an array. maybe we should implement some sort of sanity checking there.
Other than that: Nice work again man, you've earned yourself 2 gold medals :)
Kevin, a litle fix in array_product
function array_product ( input ) {
var Index = 0, Product = 1;
if ( input instanceof Array ) {
while ( Index < input.length ) {
Product *= ( !isNaN ( input [ Index ] ) ? input [ Index ] : 0 );
Index++;
}
} else {
Product = null;
}
return Product;
}
Hi Kevin, I'm attaching 3 functions more for the PHP.js project.
[CODE="Javascript"]
function array_product ( input ) {
var Index = 0, Product = 1;
if ( input instanceof Array ) {
while ( Index < input.length ) {
Product *= ( !isNaN ( input [ Index ] ) ? input [ Index ] : 0 );
Index++;
}
} else {
product = null;
}
return product;
}
function array_rand ( input, num_req ) {
var Indexes = [];
var Ticks = num_req || 1;
var Check = {
Duplicate : function ( input, value ) {
var Exist = false, Index = 0;
while ( Index < input.length ) {
if ( input [ Index ] === value ) {
Exist = true;
break;
}
Index++;
}
return Exist;
}
};
if ( input instanceof Array && Ticks <= input.length ) {
while ( true ) {
var Rand = Math.floor ( ( Math.random ( ) * input.length ) );
if ( Indexes.length === Ticks ) { break; }
if ( !Check.Duplicate ( Indexes, Rand ) ) { Indexes.push ( Rand ); }
}
} else {
Indexes = null;
}
return ( ( Ticks == 1 ) ? Indexes.join ( ) : Indexes );
}
function compact ( var_names ) {
var Index = 0, Matrix = {};
var Process = function ( value ) {
for ( var i = 0; i < value.length; i++ ) {
var key_value = value [ i ];
if ( key_value instanceof Array ) {
Process ( key_value );
} else {
if ( typeof window [ key_value ] !== 'undefined' ) {
Matrix [ key_value ] = window [ key_value ];
}
}
}
return true;
};
Process ( arguments );
return Matrix;
}
[/CODE]


Micky
Feb 23rd
01/01/2020 12h00:00
mktime(js) return 1152784800
instead of 1577876400 (mktime php)
why i don't know but it's strange...