MongoImport Dates Occurring Before The Epoch - mongodb

I am writing a utility at work which converts our relational DB at work to a complex JSON object and dumps to files grouped by subject. I then would like to import these files into MongoDB collections using the mongoimport tool.
Our data includes timestamps which represent dates occurring before the epoch, the appropriate JSON representation of which yields negative numbers. While MongoDB itself will handle these fine, the import tools JSON parser uses unsigned long long variables and fails.
If you use Mongo's special JSON date representation format ({"key": { "$date": "value_in_ticks" } }), the import tool will throw an error on those documents and skip the import. You can also use the JavaScript date notation ({"key": new Date(value_in_ticks) }) which will be successfully imported but parsed as an unsigned value creating a garbage date.
The special date format fails because of an assertion checking for reserved words. This code is reached because the presence of the negative sign at the beginning of the value causes the special date parsing to exit and return to normal document parsing.
The code to parse JSON dates explicitly calls the boost library uint_parser. There exists a signed version of this function and an issue on their JIRA tracker already exists to utilize it (on which I commented that I would attempt).
Short of diving into the code immediately to try and update this to be signed, is there an alternate route that I can take to load these dates for now?
I want to run this nightly via cron for a few months for testing so I would prefer it be very easy. These dates exist in many different parts of documents in many different collections so the solution should be generalized.

A little late to the party, but I have just come up against the same issue.
My workaround was to import the dates as strings (e.g. "1950-01-01"), and to script the conversion using Ruby on Rails with Mongoid:
Dates.each do |d|
d.mydate = d.mydate.to_date
d.save
end
Hopefully you can adapt this to whatever language/framework you are using.

This Python snippet works for me.
import time, struct
def bson_datetime(adatetime):
try:
ret = int(1000*(time.mktime(adatetime.timetuple()) + 3600))
if ret < 0:
ret = struct.unpack('Q', struct.pack('q', ret))[0]
return {'$date': ret}
except ValueError:
return None
I.e.
import datetime
print bson_datetime(datetime.datetime(1950, 12, 30, 0, 0))
yields {"abc" : {"$date" : 18446743473920751616}}.

Step 1: go to groups.google.com/group/mongodb-user and post the issue "mongoimport does not support dates before the epoch". Response times on the groups tend to be very good.
Step 2: think of running dates in a universally accepted format like "1964-04-25 13:23:12"
It will take a little bit more space in MongoDB because you'll be storing string. However it should be easy to interpret for anyone pulling out the data.

Related

Export Calendar Date to spreadsheetout - Time Stripped off - Google Script

I am using Google Script to export some calendar events to a spreadsheet; the relevant portion of my script is below:
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), myformula_placeholder, ('')]];
var range=sheet.getRange(row,1,1,7);
range.setValues(details);
This code works but the "time" that is put into the spreadsheet is a real number of the form nnnnn.nn. On the spreadsheet itself the date looks great using the integer to the left of the decimal (eg 10/15/2017) but the decimals are part of the value and therefore are part of the spreadsheet value.
My script drops the data into a sheet in my workbook, and another sheet reads the rows of data with the above date types, looking for specific date info from the other sheet using the match function (for today()). That would work fine if I could get rid of the decimals.
How can I use what I have above (if I stray far from what I have found works I will be redoing hours of work) but adding just what is needed to only put into the output spreadsheet the whole number portion so I have a pure date that will be found nicely by my match function using today()?
I have been digging, but errors abound in trying to put it all together. "Parse" looked like a good hope, but it failed as the validation did not like parse used within getStartTime. Maybe I used it in the wrong manner.
Help would be appreciated greatly.
According to the CalendarApp documentation, getStartTime() generates a Date object. You should be able to extract the date and time separately from the date object:
var eventStart = events[i].getStartTime(); // Returns date object
var startDate = eventStart.toDateString(); // Returns date portion as a string
var startTime = eventStart.toTimeString(); // Returns time portion as a string
You could then write one or both of these to your spreadsheet. See the w3schools Javascript Date Reference for more information:
http://www.w3schools.com/jsref/jsref_obj_date.asp
If you If you want to specify the string format, you can try formatDate in the Utilities service:
https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate-timezone-format
You could just use the Math.floor() function
http://www.w3schools.com/jsref/jsref_floor.asp
which will round the real number to an integer. Your line would then read:
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), Math.floor(events[i].getStartTime()), myformula_placeholder, ('')]];

How to handle date input in Laravel

I'm working on an app that allows the user to edit several dates in a form. The dates are rendered in the European format (DD-MM-YYYY) while the databases uses the default YYYY-MM-DD format.
There are several ways to encode/decode this data back and forth from the database to the user, but they all require a lot of code:
Use a helper function to convert the date before saving and after retrieving (very cumbersome, requires much code)
Create a separate attribute for each date attribute, and use the setNameAttribute and getNameAttribute methods to decode/encode (also cumbersome and ugly, requires extra translations/rules for each attribute)
Use JavaScript to convert the dates when loading and submitting the form (not very reliable)
So what's the most efficient way to store, retrieve and validate dates and times from the user?
At some point, you have to convert the date from the view format to the database format. As you mentioned, there are a number of places to do this, basically choosing between the back-end or the front-end.
I do the conversion at the client side (front-end) using javascript (you can use http://momentjs.com to help with this). The reason is that you may need different formats depending on the locale the client is using (set in the browser or in his profile preferences for example). Doing the format conversion in the front-end allows you to convert to these different date formats easily.
Another advantage is that you can then use the protected $dates property in your model to have Laravel handle (get and set) these dates automatically as a Carbon object, without the need for you to do this (see https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L126).
As for validation, you need can then use Laravel's built-in validation rules for dates, like this:
'date' => 'required|date|date_format:Y-n-j'
While client-side is good for UX, it doesn't let you be sure, all will be good.
At some point you will need server-side validation/convertion anyway.
But here's the thing, it's as easy as this:
// after making sure it's valid date in your format
// $dateInput = '21-02-2014'
$dateLocale = DateTime::createFromFormat('d-m-Y', $dateInput);
// or providing users timezone
$dateLocale =
DateTime::createFromFormat('d-m-Y', $dateInput, new DateTime('Europe/London'));
$dateToSave = $dateLocale
// ->setTimeZone(new TimeZone('UTC')) if necessary
->format('Y-m-d');
et voila!
Obviously, you can use brilliant Carbon to make it even easier:
$dateToSave = Carbon::createFromFormat('d-m-Y', $dateInput, 'Europe/London')
->tz('UTC')
->toDateString(); // '2014-02-21'
Validation
You say that Carbon throws exception if provided with wrong input. Of course, but here's what you need to validate the date:
'regex:/\d{1,2}-\d{1,2}-\d{4}/|date_format:d-m-Y'
// accepts 1-2-2014, 01-02-2014
// doesn't accept 01-02-14
This regex part is necessary, if you wish to make sure year part is 4digit, since PHP would consider date 01-02-14 valid, despite using Y format character (making year = 0014).
The best way I found is overriding the fromDateTime from Eloquent.
class ExtendedEloquent extends Eloquent {
public function fromDateTime($value)
{
// If the value is in simple day, month, year format, we will format it using that setup.
// To keep using Eloquent's original fromDateTime method, we'll convert the date to timestamp,
// because Eloquent already handle timestamp.
if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $value)) {
$value = Carbon\Carbon::createFromFormat('d/m/Y', $value)
->startOfDay()
->getTimestamp();
}
return parent::fromDateTime($value);
}
}
I'm new in PHP, so I don't know if it's the best approach.
Hope it helps.
Edit:
Of course, remember to set all your dates properties in dates inside your model. eg:
protected $dates = array('IssueDate', 'SomeDate');

Problems with query using timespan

I am doing a manual query to my postgresql database (using OrmLiteReadConnectionExtensions.SqlList<T>) that has a TimeSpan argument.
SericeStack.Ormlite is converting TimeSpan to ::time instead of ::interval as I would expect it.
More specifically: TimeSpan.FromDays(3) is converted to ((E'00:00:00.000000')::time)(taken form pg logs).
Is there a work around for this?
My current work-around is to use the C# string.Format for this problematic parameter instead of the safe and recommended™ #paramname supported by SqlList<T>.
This could be considered dangerous, but since the parameter is a double, I'm probably Okay.
The relevant part of the string is:
string.Format(CultureInfo.InvariantCulture, "RESTOFTHEQUERY ('{0:0.####} seconds'::interval) RESTOFTHEQUERY", timespan.TotalSeconds);
Don't forget to use CultureInfo.InvariantCulture.
For what it's worth, you can just cast a time value to interval. Demo
SELECT now()::time::interval
So append ::interval in your manual query and you should be fine - except for intervals > 24 hours of course.

How do I validate dates in a Perl CGI-script?

I'm creating a small reporting script in Perl CGI. I want to have the start/end date there to filter the events on the report. So now I wonder how to validate the input in some easy, Perl-way.
The way I generate the form with those fields is:
print textfield({-name=>'start_date', -value=>$start_date});
print textfield({-name=>'end_date', -value=>$end_date});
Then it goes to the database query.
Is there a simple, Perl-ish way to validate those dates? Not only as having the right number of characters, as this is simple enough via a regexp, but I'd like to report some error if the user enters 29.02.1999 or so.
I'll just go ahead and own up to being crazy, but what I like to do is use Time::Local, and flip the time back to epoch time, and then, when it's a nice clean integer, you can impose whatever sort of sanity check you like on it.
For general form validation you should use a nice framework like Data::FormValidator which has a Data::FormValidator::Constraints::DateTime module for date validation
Disclosure: I'm the author of Data::FormValidator::Constraints::DateTime
FormFu seems to be the popular library for handling forms in Perl these days. I believe it replaces the CGI HTML generation code, but it is quite powerful.
It includes a bunch of code for validating common data types, including dates.
You can calculate dates in Perl with Time::Local, which can be set to accept invalid times and still calculate the correct date (e.g. the 32th day of a month) or the check the dates and reject invalid dates.
I nearly always opt to convert something like this into DateTime object. And I use something like DateTimeX::Easy to help ease the process:
use DateTimeX::Easy;
my $start_date = DateTimeX::Easy->new( '30th Oct 2009' );
my $from_date = DateTimeX::Easy->new( 'today' );
say $start_date->dmy;
say $from_date->dmy;
# => 30-10-2009
# => 01-10-2009
The only caveat is that DateTime and its associated modules are a bit hefty on memory which is something you may want to keep an eye on when using it in CGI.
/I3az/

sqlite writing a date into an email

I am exporting a date value from sqlite and placing it into an email. The date appears like this
279498721.322872
I am using Objective C in an Iphone App. Does anyone know how to make this export out as a regular date whether it is all number like
2009-02-10 or anything legible?
Well, if you take the number 279498721.322872 and throw it into an NSDate object using +dateWithTimeIntervalSinceReferenceDate, you get (here in the MDT timezone): 2009-11-09 15:32:01 -0700, which was just under 4 hours ago. If that's the time you're expecting, then formatting it is as simple as using an NSDateFormatter.
However, the thing to notice is that sqlite (by default) stores dates as textual representations (unless you specify differently in the sql statement). So the real question here is "where are you getting that number from?"
echo date("Y-m-d",time(279498721.322872));
Thanks for the responses. The answer came from my Guru Alex Cone. He told me to use the following:
NSTimeInterval tempInterval = (NSTimeInterval)sqlite3_column_double(statement, 4);
The tempInterval variable can then be loaded into the the NSDate method.