Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store time-of-day in MongoDB? As a string? Give arbitrary year/month/day?

Tags:

mongodb

e.g. "23:55:00"

I'm in the process of converting a bus schedule database from Postgres to Mongo.
Postgres has a time without timezone datatype that I'm using to store stop times, and I'm having difficulty trying to figure out how to migrate that.

It doesn't seem to make much sense giving it an arbitrary year/month/day to convert it into a javascript Date object, but I do plan on doing some simple calculations with the times after the data gets parsed, to show stuff like 'next stopping time', so if I store it as a string I'll still have to convert it to something eventually to do comparisons

I'm really new to MongoDB and any advice would be greatly appreciated

like image 407
CheapSteaks Avatar asked Apr 03 '13 06:04

CheapSteaks


People also ask

How does MongoDB store time value?

Basically you have two options: Save time in type: String. Save date time in type: Date.

What format does MongoDB store dates?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

How do I add a timestamp in MongoDB?

In MongoDB, a special timestamp type is provided by BSON for the internal use and is not connected with the MongoDB's regular data type for Data. The Timestamp for internal use is of 64 bit of value, where this 64 bit is a combination of two 32 bit values.


1 Answers

You could store the time as a number (number of seconds since 00:00:00). It will be naturally sorted and easy to convert from/to hh:mm:ss format when needed.

//from 23:55:00 to the stored time
storedTime = hours * 3600 + minutes * 60 + seconds

//from the stored time to 23:55:00
hours = storedTime / 3600  // needs to be an integer division
leaves = storedTime - hours * 3600
minutes = leaves / 60
seconds = leaves - 60 * minutes
like image 58
assylias Avatar answered Oct 28 '22 09:10

assylias