Created
March 6, 2022 08:40
-
-
Save rorens05/5499310c189acd6c0a1df88a0e537291 to your computer and use it in GitHub Desktop.
Rails Daterange Integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# link | |
https://github.com/jordanbrock/bootstrap-daterangepicker-rails | |
# Gemfile | |
gem 'jquery-rails' | |
gem 'momentjs-rails' | |
gem 'bootstrap-daterangepicker-rails' | |
# application.js | |
//= require moment | |
//= require daterangepicker | |
# application.css | |
*= require bootstrap | |
*= require daterangepicker | |
# application.js | |
$(document).ready(function() { | |
$('input[class="daterange"]').daterangepicker({ | |
ranges: { | |
'Today': [moment(), moment()], | |
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], | |
'Last 7 Days': [moment().subtract(6, 'days'), moment()], | |
'Last 30 Days': [moment().subtract(29, 'days'), moment()], | |
'This Month': [moment().startOf('month'), moment().endOf('month')], | |
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] | |
} | |
}); | |
}); | |
# for a simple_form field just do something like this and include the above javascript | |
# HTML | |
input type: "text", class: "daterange", name: 'date-range', value: format_daterange(start_date, end_date) | |
# formatter | |
def format_daterange(start_date, end_date) | |
if start_date.present? && end_date.present? | |
"#{start_date.strftime('%D')} - #{end_date.strftime('%D')}" | |
else | |
'' | |
end | |
end | |
# controller | |
start_date = Date.today | |
end_date = Date.today | |
if params["date-range"].present? | |
start_date = Date.strptime(params["date-range"].split(" - ")[0], '%m/%d/%Y') | |
end_date = Date.strptime(params["date-range"].split(" - ")[1], '%m/%d/%Y') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment