↖ Writing

How to convert a Bear timestamp to JavaScript Date

How to convert a Bear timestamp to JavaScript Date

The dates in Bear’s database are written in a format like this: 731997024.768723.

It looks similar to a unix epoch timestamp, but the dates are off. I asked the Bear support team which format their database uses. They helpfully explained its a CoreData timestamp, and pointed me towards this StackOverflow question: How does the iPhone SDK Core Data system store date types to sqlite?.

This Apple Cocoa Core Data timestamp that Bear uses, calculates the seconds offset since January 1, 2001. A Unix timestamp calculates the seconds since January 1, 1970.

Since we now know the timestamp format and offset, we can convert the Bear timestamp to a JavaScript Date:

function cocoaCoreDataTimestampToDate(timestamp: number) {
  const timestampInNanoSecondsEpoch = new Date(timestamp * 1000).getTime();
  const epochOffset = new Date("2001-01-01 00:00:00 -0000").getTime();
  return new Date(timestampInNanoSecondsEpoch + epochOffset);
}

We can use this method to get the JavaScript Date from a Bear timestamp.

const date = cocoaCoreDataTimestampToDate(731997024.768723) // Wed Mar 13 2024 14:30:24 GMT+1000 (Australian Eastern Standard Time)

Thank you again, Danilo from the Bear team!

More Resources