I am working with DateTime data that is stored in the Buddhist year but I need to convert it to the Gregorian year.
There is actually a simple solution (code below).
{
"$dateSubtract": {
"startDate": {
"$dateFromString": {
"dateString": "$receive_date",
"format": "%d/%m/%Y %H:%M"
}
},
"unit": "year",
"amount": 543
}
}
It works most of the time, but throws an error if receive_date is 2/29/2567 because 2567 in the Gregorian year is not a leap year but it is in the Buddhist year.
Do you have any suggestions to resolve this issue?
The problem occurs because you first try to convert the Buddhist date to a Date object and then subtract 543 years. For dates like 29/02/2567 , MongoDB initially tries to interpret the year 2567 as Gregorian, and when subtracting years, it may result in an invalid date.
A more robust alternative is to extract the year from the string, subtract 543 before constructing the date, and then reassemble the complete value. This way, MongoDB will directly validate the date against the correct Gregorian calendar, avoiding leap year-related inconsistencies during conversion.