MyKindlebox/mykindlebox/client/src/lib/format.js

56 lines
1.5 KiB
JavaScript

export const SEX_LABELS = {
buck: 'Buck',
doe: 'Doe',
unknown: 'Unknown',
}
export function formatAge(dob) {
if (!dob) return 'Age unknown'
const birth = new Date(`${dob}T00:00:00`)
if (Number.isNaN(birth.getTime())) return 'Age unknown'
const today = new Date()
let years = today.getFullYear() - birth.getFullYear()
let months = today.getMonth() - birth.getMonth()
if (today.getDate() < birth.getDate()) months -= 1
if (months < 0) {
years -= 1
months += 12
}
if (years < 0) return 'Age unknown'
if (years === 0 && months === 0) return '<1m'
if (years === 0) return `${months}m`
if (months === 0) return `${years}y`
return `${years}y ${months}m`
}
// Weight is always stored as decimal lbs; the `unit` argument (the user's
// `weight_unit` setting — see useWeightUnit) only controls display. lbs+oz
// rounds to the nearest ounce, carrying 16oz up to a pound so you never see
// "3 lb 16 oz".
export function formatWeight(weightLbs, unit = 'decimal_lbs') {
if (weightLbs === null || weightLbs === undefined || weightLbs === '') return null
const value = Number(weightLbs)
if (Number.isNaN(value)) return null
if (unit === 'lbs_oz') {
const totalOz = Math.round(value * 16)
const lbs = Math.floor(totalOz / 16)
const oz = totalOz % 16
return `${lbs} lb ${oz} oz`
}
return `${value.toFixed(2)} lbs`
}
export function formatDate(isoDate) {
if (!isoDate) return null
return new Date(`${isoDate}T00:00:00`).toLocaleDateString('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric',
})
}