首页 > 解决方案 > How to check if it's somebody's birthday in JS (with time zone)?

问题描述

Earlier I asked about the concepts of storing birth dates and notifying users, after looking at some libraries I decided to go for date-fns and date-fns-tz, I figured I can store dates like this:

import { utcToZonedTime, zonedTimeToUtc } from "date-fns-tz";

// Picked by user
const timeZone = "America/Los_Angeles";
const birthDate = "03-11";

const utcDate = zonedTimeToUtc(`2000-${birthDate} 00:00:00`, timeZone);

// Stored in database
console.log(utcDate.toISOString(), timeZone);

I am still missing the concept because I am stuck at the part where I check if it's somebody's birthday regardless of where my server is hosted, let's say I run a cron job at 0 0 * * *, how would I know which people to message? I accept either a postgres or JavaScript solution (or combined)

标签: javascriptpostgresqldatetimezonedate-fns

解决方案


We can make the PostgreSQL query like this

SELECT * FROM TABLE_NAME 
WHERE
     DATE_PART('day', DOB) = date_part('day', CURRENT_DATE)
AND
     DATE_PART('month', DOB) = date_part('month', CURRENT_DATE)
AND
     cast(DOB as time) >= localtime;

where DOB is the birthdate stored.


Another solution which will acount for leap years as well

SELECT * FROM TABLE_NAME
WHERE
EXTRACT(YEARS FROM age(CURRENT_TIMESTAMP, DOB)) > user_age;

age is an inbuilt function which takes cares of the leap years as well, we can store the user_age of the user and update when it changes.


推荐阅读