Created
February 28, 2018 12:21
-
-
Save schuhwerk/a3135a2d9e42c44099d839d73e46ddef to your computer and use it in GitHub Desktop.
Use a variable PHP datestring to format a date in Javascript
This file contains 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
/** | |
* Localize a Datepicker / Timepicker (flatpickr) | |
* Format PHP datestring to js and vice versa | |
* | |
* fromPhp is the variable that gets passed via wordpress wp_localize_script | |
* fromPhp.dateFormat get_option( 'date_format' ); | |
* fromPhp.timeFormat get_option( 'time_format' ); | |
*/ | |
//https://github.com/kartik-v/php-date-formatter | |
var dateFormatter = new DateFormatter(); //php to js date format | |
//https://flatpickr.js.org/examples/#datetime | |
var picker = $('#datepicker').flatpickr({ | |
altInput: true, | |
enableTime: true, | |
time_24hr: fromPhp.twentyfour, //24h vs. AM/PM | |
defaultHour: 00, //default is 12 but we use 00:00 as "all day" | |
defaultMinute: 00, | |
parseDate: function(date) { | |
return dateFormatter.parseDate(date, 'Y-m-d H:i:s'); //this is the default format we use in the database | |
}, | |
onChange: function(selectedDates, datestr, instance){ | |
dateObj = selectedDates[0]; //select first of the selected dates | |
var phpFormat = dateFormatter.formatDate(dateObj, 'Y-m-d H:i:s'); | |
/* the fomatDate method formats both the real and the altInput field. | |
* So we formate the real Input field again to be compatible with php | |
* Might be easier to just use a unix date... */ | |
picker.input.value = phpFormat; //this | |
}, | |
formatDate: function(dateObj, formatString) { | |
var dateTime = fromPhp.dateFormat+' '+fromPhp.timeFormat; //get the php date format | |
return dateFormatter.formatDate(dateObj, dateTime); //use the php date formate to show the date object | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment