Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:54
Show Gist options
  • Save dotproto/ae4eead8f7a97620e963 to your computer and use it in GitHub Desktop.
Save dotproto/ae4eead8f7a97620e963 to your computer and use it in GitHub Desktop.
Convert a Firebase Push ID into Unix time (https://gist.github.com/mikelehen/3596a30bd69384624c11/)
var getPushIdTimestamp = (function getPushIdTimestamp() {
var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
return function getTimestampFromId(id) {
var time = 0;
var data = id.substr(0, 8);
for (var i = 0; i < 8; i++) {
time = time * 64 + PUSH_CHARS.indexOf(data[i]);
}
return time;
}
})();
@dotproto
Copy link
Author

The first version of this function was implemented in a more functional style. Out of curiosity I thought I'd try an imperative approach and compare the results.

timestamp functional x 576,229 ops/sec ±2.58% (91 runs sampled)
timestamp imperative x 2,438,362 ops/sec ±4.73% (91 runs sampled)

This test was performed on Node 0.12.5 using Benchmark.js.

@Maqix
Copy link

Maqix commented Nov 25, 2016

`
func toTimeStamp() -> TimeInterval {

   func toTimeStamp() -> TimeInterval {
    guard self.characters.count == 20 else { return 0 }
    var PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
    var time: TimeInterval = 0
    let endDatePartOffset = 8
    let range = Range(uncheckedBounds: (lower: self.startIndex, upper: self.index(self.startIndex, offsetBy: endDatePartOffset)))
    var data = self.substring(with: range)
    for i in 0...(endDatePartOffset - 1) {
        let char = Array(data.characters)[i]
        let indexOfChar = Array(PUSH_CHARS.characters).index(of: char)!
        time = time * 64 + Double(indexOfChar)
    }
    return time
}`

Swift 3 version, thank you ;)

@Voyz
Copy link

Voyz commented Dec 13, 2016

Java port:

private final static String PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
public static long getTimestampFromId(String id) {
    long time = 0;

    String data = id.substring(0, 8);

    for (int i = 0; i < 8; i++) {
        time = time * 64 + PUSH_CHARS.indexOf(data.charAt(i));
    }

    return time;
}

@JuanPTM
Copy link

JuanPTM commented Dec 16, 2017

Python 2.X/3.X port:

def keyToTimeStamp(key):
        PUSH_CHARS ='-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
        idString = key[0:8]
        time = 0
        for letter in idString:
                time = time * 64 + PUSH_CHARS.index(letter)

        return time 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment