Skip to content

Instantly share code, notes, and snippets.

@mmarienko
Last active April 11, 2023 22:55
Show Gist options
  • Save mmarienko/07de50a6811c4f35c665cbc47a689c44 to your computer and use it in GitHub Desktop.
Save mmarienko/07de50a6811c4f35c665cbc47a689c44 to your computer and use it in GitHub Desktop.
noUiSlider - relative date
// Return milliseconds from a count of day.
function getMsFromDay(day) {
return day * 86400000;
}
// Setup
var relativeDateSlider = document.getElementById('slider-relative-date');
noUiSlider.create(relativeDateSlider, {
start: getMsFromDay(30),
connect: [true, false],
range: {
min: getMsFromDay(30),
max: getMsFromDay(1825),
},
step: getMsFromDay(1),
});
// Slider control
var relativeDateValues = document.getElementById('relative-date-value');
relativeDateSlider.noUiSlider.on('update', function (values, handle) {
relativeDateValues.innerHTML = formatDate(new Date(+values[handle]));
});
// Helper function and formatting
function formatDate(date) {
const IntlTime = new Intl.RelativeTimeFormat('en');
let year, month, day;
let yearIntl = IntlTime.formatToParts(date.getYear() - 70, 'year');
let monthIntl = IntlTime.formatToParts(date.getMonth(), 'month');
let dayIntl = IntlTime.formatToParts(date.getDate(), 'day');
year = date.getYear() - 70 ? (yearIntl[1] ? yearIntl[1].value + yearIntl[2].value + ',' : yearIntl[0].value + ',') : '';
month = +date.getMonth() ? (monthIntl[1] ? monthIntl[1].value + monthIntl[2].value + ',' : monthIntl[0].value + ',') : '';
if ((new Date(date.getYear(), date.getMonth(), date.getDate() + 1)).getDate() != 1) {
day = dayIntl[1] ? dayIntl[1].value + dayIntl[2].value : dayIntl[0].value;
} else if ((date.getMonth() + 1) != 12) {
day = '';
monthIntl = IntlTime.formatToParts(date.getMonth() + 1, 'month');
month = monthIntl[1] ? +monthIntl[1].value + monthIntl[2].value : monthIntl[0].value;
} else {
day = month = '';
yearIntl = IntlTime.formatToParts(date.getYear() - 69, 'year');
year = yearIntl[1] ? +yearIntl[1].value + yearIntl[2].value : yearIntl[0].value;
}
return `${year} ${month} ${day}`;
}
.example {
position: relative;
padding: 40px 40px 50px 40px;
margin: 20px 0;
overflow: hidden;
}
.example-val:before {
content: "Value: ";
font: 700 12px Arial;
}
.example-val {
font: 400 12px Arial;
color: #888;
display: block;
margin: 15px 0;
}
<div class="example">
<div id="slider-relative-date"></div>
<span class="example-val" id="relative-date-value"></span>
</div>
@mmarienko
Copy link
Author

@mmarienko
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment