0

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.

Craig
  • 2,093
  • 3
  • 28
  • 43
  • 1
    That's basically representing the date as the number of seconds from some epoch... e.g. unix time. – Dan Mašek May 07 '19 at 23:52
  • 1
    However, what you seem to want to do is to use base36 encoding... this will cause a significant expansion -- you'll need 7 symbols to represent any 32bit integer. – Dan Mašek May 08 '19 at 00:00
  • 1
    As @DanMašek said, use the standard count of seconds since the Unix epoch and then look up an algorithm to print in base (radix) 36. That should be described in many places. The seconds for this century go up to 4 102 444 799 (depending on time zone), which can be represented in 7 digits base 36 (36^6 is 2 176 782 336, which is not enough, but 36^7 is 78 364 164 096, which is plenty). – Ole V.V. May 08 '19 at 09:18
  • @OleV.V. Thanks for pointing me in the right direction. – Craig May 08 '19 at 13:32

1 Answers1

1

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());
Craig
  • 2,093
  • 3
  • 28
  • 43