Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Applying custom functions directly in GROQ for data destructuring from datetime.

5 replies
Last updated: Oct 10, 2023
Hi all, I'm wondering if there is a way apply function to destructure data from datetime like hour, year etc. directly in GROQ something like this:

*[_type == "open_course" && is_active == true]{ 
in_person{
  'year' : new Date(start_date).getFullYear()
   }
  }
 }
Any gists or ideas as
datetime()
doesn't explain much. It is more about using custom function directly in GROQ to return values I need . Or there is no way to apply such functionality and I have to process data when I receive these from Sanity?
Oct 10, 2023, 8:44 AM
perhaps it's doable with some clever chaining of
string::split()
?
Oct 10, 2023, 12:17 PM
"year": string::split(start_date, '-')[0]
Oct 10, 2023, 12:18 PM
groq isn't javascript πŸ˜„
Oct 10, 2023, 12:19 PM
Yeh, I have found it too, I'm GROQ newbie and its syntax is not intuitive and looks scary to me :), sorry. String split is not I would like to do but thank you. In meantime I have sorted with utility functions and it works for me.
/**
 * @param {string | number | Date} date
 */
function formatTime(date) {
	var d = new Date(date),
		hours = '' + d.getHours(),
		minutes = '' + d.getMinutes();

	if (hours.length < 2) hours = '0' + hours;
	if (minutes.length < 2) minutes = '0' + minutes;

	return [hours, minutes].join(':');
}

/**
 * @param {string | number | Date} date
 */
function formatDateMonthName(date) {
	var d = new Date(date),
		month = '' + (d.getMonth() + 1),
		day = '' + d.getUTCDate(),
		year = d.getUTCFullYear();
	if (month.length < 2) month = '0' + month;
	if (day.length < 2) day = '0' + day;
	// @ts-ignore
	const monthStr = months[parseInt(month)];
	return `${monthStr} ${day}, ${year}`;
}
Will dig into GROQ a bit deeper when I will have time. Any suggestions of some great sources with beside official docs?
Oct 10, 2023, 7:18 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?