-
Notifications
You must be signed in to change notification settings - Fork 67
Description
The sample code below is provided on Quick Start
function getTimeAgoDescription(dateString) {
const startDate = new Date(dateString);
const currentDate = new Date();
const years = currentDate.getFullYear() - startDate.getFullYear();
const months = currentDate.getMonth() - startDate.getMonth();
const days = currentDate.getDate() - startDate.getDate();
let timeAgoDescription = '';
if (years > 0) {
timeAgoDescription += `${years} ${years === 1 ? 'year' : 'years'}`;
}
if (months > 0) {
if (timeAgoDescription !== '') {
timeAgoDescription += ' ';
}
timeAgoDescription += `${months} ${months === 1 ? 'month' : 'months'}`;
}
if (days > 0) {
if (timeAgoDescription !== '') {
timeAgoDescription += ' ';
}
timeAgoDescription += `${days} ${days === 1 ? 'day' : 'days'}`;
}
if (timeAgoDescription === '') {
timeAgoDescription = 'today';
} else {
timeAgoDescription += ' ago';
}
return timeAgoDescription;
}
Short version of the problem is that I never got the code to pass unit tests until I modified the code as follows (see comments about timezone):
function getTimeAgoDescription(dateString) {
const startDate = new Date(dateString + 'T00:00:00'); // Add time to avoid timezone issues
const currentDate = new Date();
...
}
Ironically, I reverted to good old Stackoverflow for the answer.
I say ironic because at no time and regardless of the amount of context or passing code into Cody Chat did it ever suggest the issue was js Date() defaults to UTC when passed a date string without a time/timezone. All the tests were failing (off by one day).
I would think this is exactly the kind of code assistance (pair programming) Cody is ideally suited for:
Cody: "Hey buddy, your intention is probably to get a date in your local timezone and if you pass only a date string, you'll get UTC instead.
Me: Thanks Cody, appreciate you got my back.