Published
Edited
Nov 18, 2020
Importers
Insert cell
md`# date formatters`
Insert cell
d3 = require("d3")
Insert cell
function leapYear(year) {
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
}
Insert cell
yearFormat = d3.timeFormat("%Y")
Insert cell
dayDemicalFormat = d3.timeFormat("j%")
Insert cell
function dateToDecimal(date){
const year = parseInt(d3.timeFormat("%Y")(date));
const day = parseInt(d3.timeFormat("%j")(date));
const totalNumberOfDays = leapYear(year)? 366:365;
return year+day/totalNumberOfDays
}
Insert cell
function decimalToDate(decimal){
const year = Math.trunc(decimal);
const totalNumberOfDays = leapYear(year)? 366:365;
const day = Math.round(((decimal-year)*totalNumberOfDays))
return d3.timeParse("%Y-%j")(`${year}-${day}`)

}
Insert cell
formatDate =(f)=> (d) => {
const dateFormat = d3.timeFormat(f);
return `${dateFormat(decimalToDate(d))}`;
};

Insert cell
decimalToDate((dateToDecimal(new Date)))
Insert cell
parseFloat("2019-20")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more