Question

I've converted a whole heap of datestrings into unix timestamps (as milliseconds since epoch).

I used the moment.js date library which did a great job except there was one misunderstanding. In Australia, dates are usually represented in the format DD/MM/YYYY, however American dates are MM/DD/YYYY and moment seems to have assumed that the dates I parsed are in the American format.

This has lead to dates such as 01/10/2000 to be parsed as the tenth of January rather than the first of October. I've stored these dates as a number representing moments since epoch, so the date above has been stored as 970322400000 rather than 947426400000.

I want to convert all of the dates I've calculated into their proper values. I need a function which will take 970322400000 and convert it to 947426400000 for all dates that have been incorrectly calculated. Due to other circumstances I am unable to reprocess the dates from their original source.

Unfortunately - I have to run this in the mongodb shell.

Here is what I have already tried (the minified source of moment js at the top of the file).

db.reminders.find()
.map(function(v) {
    return {
        id: v._id,
        original: moment(v.reminderDate).format('YYYY-MM-DD'),
        repaired: moment(moment(moment(v.reminderDate).format('MM-DD-YYYY'), 'DD-MM-YYYY').valueOf()).format('YYYY-MM-DD')
    };
})

However I'm afraid it's not working. In the outputted results I can't find any dates with a day component higher than 12.

What am I doing wrong here. How am I able to achieve this transformation?

Était-ce utile?

La solution

This is actually an impossible problem. This is due to the fact that a value larger than 12 in the months part will flow over into the year.

'01-01-2012' -> x

'01-13-2011' -> x

'01-25-2010' -> x

There are infinity date-strings which can be evaluated for any given unix timestamp. Therefore you can't know what the original datestring was. This makes it impossible to change a timestamp value to the value that it would have been if it was parsed differently.

Fair warning with these sorts of problems, store the original datestring. If you need to have the date stored as a number for some reason it doesn't matter - store the original as well.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top