Search code examples
datecompressionbitradix

Compress date to unique alphanumeric characters


If I have a date YYMMDDHHmmss such as 190525234530 how do I work out the smallest number of characters to represent this using 0-9a-z (36 characters)?

I believe there are 3,153,600,000 combinations (100 years * 365 days * 24 hours * 60 minutes * 60 seconds) which would fit into 32 bits. Does this mean I could represent these dates using 4 characters?

I am a bit lost as to how to do the conversion so if anyone could show me the maths that would be greatly appreciated.


Solution

  • I ended up doing this in JavaScript, I decided I wanted to compress to 6 characters so I created my own time which generates unique ID's for up to 68 years from 01/01/2019 which worked for me.

    function getId() {
      //var newTime = parseInt(moment().format("X")) - 1546300800;//seconds since 01/01/2019
      var newTime = Math.floor((new Date()).getTime() / 1000) - 1546300800;//seconds since 01/01/2019
      var char = "0123456789abcdefghijklmnopqrstuvwxyz";//base 36
      return char[Math.floor(newTime / 36**5)]+
      char[Math.floor(newTime%36**5 / 36**4)]+
      char[Math.floor(newTime%36**4 / 36**3)]+
      char[Math.floor(newTime%36**3 / 36**2)]+
      char[Math.floor(newTime%36**2 / 36)]+
      char[Math.floor(newTime%36)];
    }
    console.log(getId());

    Thanks to @user956584 this can be be changed to:

    function getId() {
      //var newTime = parseInt(moment().format("X")) - 1546300800;//seconds since 01/01/2019
      var newTime = Math.floor((new Date()).getTime() / 1000) - 1546300800;//seconds since 01/01/2019
      return newTime.toString(36);
    }
    console.log(getId());