As moment is deprecated, I decided to stash moment from my entire project and thinking to use datefns as a replacement. While I was going through the code file, I came across a line which is saying,
moment(date1).isSameOrBefore(date2, year);
I started looking for something that is similar to what that function is doing but unfortunately, date-fns doesn't have anything to perform precision-based comparison (i.e: year, month or date comparison)? Can anyone suggest some workaround with date-fns?
You should be able to create a drop-in replacement, as long as you test against the relevant moment function.
We can look for the relevant startOfXXX procedure to compare dates when the unit
is specified, and also throw an error if it is missing:
function isSameOrBefore(date1, date2, unit = '') {
if (unit) {
const procName = `startOf${unit[0].toUpperCase()}${unit.slice(1)}`;
if (!dateFns[procName]) {
throw new Error(`isSameOrBefore: Unsupported unit: ${unit}`);
}
date1 = dateFns[procName](date1);
date2 = dateFns[procName](date2);
}
return dateFns.isBefore(date1, date2) || dateFns.isEqual(date1, date2);
}
// Test against various inputs
const dts = ['2010-10-20 01:00', '2010-10-20 00:00', '2010-10-20 00:59:00', '2010-10-01', '2010-09-01', '2009-09-01'];
let units = ['year', 'month', 'day', 'hour', 'minute'];
let dt1 = '2010-10-20 01:00'
let allTests = [];
for(let dt2 of dts) {
for(let unit of units) {
// Ensure we get the same answer as moment().isSameOrBefore
const testPassed = isSameOrBefore(dt1, dt2, unit) === moment(dt1).isSameOrBefore(dt2, unit)
allTests.push(testPassed);
console.log(`isSameOrBefore(${dt1}, ${dt2}, ${unit}):`, isSameOrBefore(dt1, dt2, unit));
console.log(`isSameOrBefore(${dt1}, ${dt2}, ${unit}): Test passed:`, testPassed ? "TRUE": "FALSE")
}
}
console.log("All tests passed:", allTests.every(res => res) ? "TRUE": "FALSE")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js" integrity="sha512-F+u8eWHrfY8Xw9BLzZ8rG/0wIvs0y+JyRJrXjp3VjtFPylAEEGwKbua5Ip/oiVhaTDaDs4eU2Xtsxjs/9ag2bQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>