Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="canvas-wrapper">
  <canvas id="histogram"></canvas>
</div>

              
            
!

CSS

              
                blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
  margin: 0;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: inherit;
  font-weight: inherit;
}

ol,
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
  display: block;
  vertical-align: middle;
}

*,
::before,
::after {
  border-width: 0;
  border-style: solid;
  border-color: theme('borderColor.DEFAULT', currentColor);
}

.google-map * {
  border-style: none;
}

button:focus {
  outline: 1px dotted;
  outline: 5px auto -webkit-focus-ring-color;
}

.canvas-wrapper {
  margin: 4rem 15rem;
}

              
            
!

JS

              
                /**
 * Parse date string in yyyy-mm-dd format.
 *
 * Date() doesn't parse strings properly.
 * For example, if you pass a string directly in:
 * Date('2021-07-01'), Date() will return 2021 06 30.
 */
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}


/**
* Get the days between endDate and startDate.
* Place those days in daysInRange.
*/
function getTotalDays(endDate, startDate) {
  let dateDecrement = endDate
  let daysInRange = []
  daysInRange.push(endDate)
  for (let i = 0; daysInRange[i] > startDate; i++) {
    dateDecrement.setDate((dateDecrement.getDate() - 1))
    daysInRange.push(dateDecrement)
    dateDecrement = new Date(dateDecrement)
  }

  /**
  * Check if the date range looks correct.
  */
  console.log(`daysInRange:`)
  console.log(JSON.stringify(daysInRange))

  return daysInRange = daysInRange.reverse()

}


/**
 * Build the month increments.
 */
function getMonthList(daysInRange) {
  let monthList = []
  for (let i = 0; i < daysInRange.length; i++) {
    /**
    * Get the current month and the following month
    * Push them to matchList
    */
    if (monthList[monthList.length - 1]) {
      const comparison = monthList[monthList.length - 1].getMonth() ==
                          daysInRange[i].getMonth()
      if (!comparison) {
        monthList.push(daysInRange[i])
      }
    } else {
      monthList.push(daysInRange[0])
    }
  }

  /**
  * Check if monthList looks correct.
  */
  console.log(`monthList:`)
  console.log(monthList)

  return monthList
}


/**
 * Build the month increments.
 */
function getMonthRanges(monthList, dates) {
  let monthRanges = []
  for (let i = 0; i < monthList.length; i++) {
    if(monthList[i] !== monthList[monthList.length] && monthList[i + 1] !== undefined) {
      const monthRange = {
        // x: monthList[i].toISOString().split('T')[0] + " - " +
        //     monthList[i + 1].toISOString().split('T')[0],
        x: [monthList[i], monthList[i + 1]],
        y: 0
      }
      monthRanges.push(monthRange)
    } else if (monthList[i] !== monthList[monthList.length] && monthList[i + 1] === undefined) {
      /**
      * Fill in the last month.
      */
      const secondToLastMonth = new Date(monthList[i])
      const lastMonth = secondToLastMonth.setMonth(monthList[i].getMonth() + 1)
      const monthRange = {
        x: [monthList[i], lastMonth],
        y: 0
      }
      monthRanges.push(monthRange)
    }
  }

  /**
  * Check if the month ranges look correct.
  */
  // console.log(`monthRanges:`)
  // console.log(monthRanges)

  /**
  * Determine how many of the given dates are in each bucket.
  */
  for (let i = 0; i < dates.length; i++) {
    for (let j = 0; j < monthRanges.length; j++) {
      if (dates[i] >= monthRanges[j].x[0] && dates[i] <= monthRanges[j].x[1]) {
        monthRanges[j].y += 1
      }
    }
  }

  /**
  * Check the result
  */
  console.log(`monthRanges updated:`)
  console.log(monthRanges)

  return monthRanges
}


/**
 * Plot a histogram of the results
 */
export function makeMonthListHistogram(monthList, monthRanges) {
  const labels = monthList.map((month) => {
    return month.toLocaleString(
      'default',
      {month: 'long'}
    )
  })

  const backgroundColors = monthRanges.map((month, index) => {
      return `hsla(${((360) * index)/(monthRanges.length)}, ${100}%, ${69}%,  0.4)`
  })

  const borderColors = monthRanges.map((month, index) => {
    return `hsla(${((360) * index)/(monthRanges.length)}, ${100}%, ${69}%,  1)`
  })

  const data = {
    labels: labels,
    datasets: [{
      label: '# of dates in date range',
      data: monthRanges.map((date) => {
        return date.y
      }),
      backgroundColor: backgroundColors
      ,
      borderColor: borderColors,
      borderWidth: 1
    }]
  }

  const config = {
    type: 'bar',
    data: data,
    options: {
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            stepSize: 1
          }
        }
      }
    }
  }

  const histogram = new Chart(
    document.getElementById('histogram'),
    config
  )

  return histogram
}


function dateTimeChallenge(endDate, startDate, dateList) {
  /**
  * Convert startDate and endDate, so we can get the date range
  */
  startDate = parseDate(startDate)
  endDate = parseDate(endDate)

  /**
  * Convert dateList to dates objects.
  */
  const dates = dateList.map((date) => {
    return parseDate(date)
  })

  const totalDays = getTotalDays(endDate, startDate)
  const monthList = getMonthList(totalDays)
  const monthRanges = getMonthRanges(monthList, dates)

  makeMonthListHistogram(monthList, monthRanges)
}


const startDate = '2021-07-05'
const endDate = '2021-11-05'

const dateList = [
  '2021-07-05',
  '2021-07-08',
  '2021-08-05',
  '2021-08-14',
  '2021-08-25',
  '2021-09-05',
  '2021-09-16',
  '2021-09-25',
  '2021-09-28',
  '2021-10-02',
  '2021-10-10',
  '2021-11-11',
  '2022-03-05',
  '2022-03-09'
]

dateTimeChallenge(endDate, startDate, dateList)

              
            
!
999px

Console