» Javascript equivalent for PHP's mktime

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: mktime.

PHP mktime

Description

mktime - Get Unix timestamp for a date

int mktime([ int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Parameters

  • hour

    The number of the hour.

  • minute

    The number of the minute.

  • second

    The number of seconds past the minute.

  • month

    The number of the month.

  • day

    The number of the day.

  • year

    The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit signed integer, as most common today, the valid range for year is somewhere between 1901 and 2038. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

  • is_dst

    This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but not incorrect) results. Some times are invalid if DST is enabled on the system PHP is running on or is_dst is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is enabled is evaluated as 23:30 of the previous day.

    Note: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

Return Values

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

See Also

Javascript mktime

Source

This is the main source of the Javascript version of PHP's mktime

function mktime() {
    // http://kevin.vanzonneveld.net
    // +   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
    // *     example 1: mktime( 14, 10, 2, 2, 1, 2008 );
    // *     returns 1: 1201871402
    
    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); }
    };
    
    for( i = 0; i < argc; i++ ){
        no = parseInt(argv[i]);
        if(no && isNaN(no)){
            return false;
        } else if(no){
            // arg is number, let's manipulate date object
            if(!dateManip[i](no)){
                // failed
                return false;
            }
        }
    }
 
    return Math.floor(d.getTime()/1000);
}

Examples

Currently there is 1 example

Example 1

This is how you could call mktime()
mktime( 14, 10, 2, 2, 1, 2008 );
And that would return
1201871402

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it



Testing the functions

The number of functions is growing fast and so it becomes hard to maintain quality.

To defeat that danger of bad code, syntax errors, etc, I've added a new feature: php.js tester.

It is an automatically generated page that includes ALL functions in your browser, and then extracts specific testing information from each function's comments. This info is then used to run the function, and the return value is compared to a predefined one.

This way code is always checked on syntax errors, and if it doesn't function correctly anymore after an update, we should also be able to detect it more easily.

If you want, go check it out.


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedal_argos for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalPhilip Peterson for contributing to:
 sizeof, round, echo, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalMartijn Wieringa for contributing to:
 str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBrett Zamir for contributing to:
 str_split
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPhilippe Baumann for contributing to:
 empty
spacemedalSakimori for contributing to:
 strlen
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedalkenneth for contributing to:
 explode
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalstensi for contributing to:
 intval

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Versioning. Individual functions are versioned, but the entire library should be versioned as well.
  • Light. A lightweight version of php.js should be made available with only common functions in it.

Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript, phpjs
category: Programming - Javascript - PHP equivalents
read: 4,528 times

Add comment

for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#20. Kevin on 22 April 2008

Kevin@ 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

+(date.getTimeZoneOffset() * 60 * 60);
In the test to neutralize the end user's timezone?

#19. Kevin on 22 April 2008

Kevin@ 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!

#18. Philip Peterson on 21 April 2008

Philip PetersonHmm, 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?

#17. Kevin on 20 April 2008

Kevin@ Philip Peterson: Yeah that's related to the different timezones that we are in.

#16. Philip Peterson on 20 April 2008

Philip PetersonJust 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...

#15. Kevin on 19 April 2008

Kevin@ FGFEmperor: Thanks a lot!

#14. FGFEmperor on 18 April 2008

FGFEmperorOK, now setting a month to something greater than 11 would not increase the year... My correction (also for hours, minutes and seconds...

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); }
    };
Basically I added 'ma' and 'mb' to the vars, and summed that on Years and Days... =)

#13. Kevin on 02 April 2008

Kevin@ FGFEmperor: Good work man, thanks a lot, I'll update the function!

#12. FGFEmperor on 31 March 2008

FGFEmperorOK, another update:
change
d.setYear(1970);
to
d.setYear(1972);
... [more] Why? Because this way Leap Years are gonna work.

#11. FGFEmperor on 31 March 2008

FGFEmperorGot It! Add

d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1970);
after
var no, i = 0, d = new Date(), argv = arguments, argc = argv.length;
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). ;-)

#10. FGFEmperor on 31 March 2008

FGFEmperorI 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
... [more] Any idea why? That way, I should get 4/5/2009 for both, but I'm getting 5/5/2009 on the JS version...

#9. Kevin on 23 March 2008

Kevin@ 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!

#8. gabriel paderni on 22 March 2008

gabriel paderniIf i'm not mistaken there's a bug when using strings as parameters: here is the test I've made:

<script type="text/javascript">
function mktimetest(t_php,t_js){
  document.write(t_php+'
'+t_js);
  if(t_php!=t_js)document.write(' &lt;- Error');
  document.write('
 
');
}
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>
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.)

#7. Kevin on 02 March 2008

Kevin@ Michael White: Tried to reproduce the behavior, but wasn't able to:
http://kevin.vanzonneveld.net/test.php

#6. Michael White on 02 March 2008

Michael WhiteThe 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:

// *     example 1: mktime( 14, 10, 2, 2, 1, 2008 );
    // *     returns 1: 1201893002

#5. Kevin on 21 February 2008

Kevin@ baris ozdil: Thank your for your contribution, I've updated php.js and included you in the credits!

#4. baris ozdil on 21 February 2008

baris ozdilHi 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:

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); }
    };

#3. Kevin on 03 February 2008

Kevin@ _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 :)

#2. _argos on 03 February 2008

_argosKevin, a litle fix in array_product

function array_product ( input ) {
var Index = 0, Product = 1;

... [more] if ( input instanceof Array ) {
while ( Index < input.length ) {
Product *= ( !isNaN ( input [ Index ] ) ? input [ Index ] : 0 );
Index++;
}
} else {
Product = null;
}

return Product;
}

#1. _argos on 03 February 2008

_argosHi Kevin, I'm attaching 3 functions more for the PHP.js project.

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;
}