datepicker icon indicating copy to clipboard operation
datepicker copied to clipboard

Show and store date in different format

Open vnyv opened this issue 6 years ago • 3 comments

It will be great if have a feature to store the Date in specified format and display in a different format.

vnyv avatar Jun 21 '18 12:06 vnyv

+1 I'm struggling to give users a friendly to use UI, but the code / database require the date in a specific format. Thus I would need a hidden field which is included in the POST data and where the data is stored in a database friendly way.

chtheis avatar Oct 22 '18 13:10 chtheis

Try this:

$().on( 'pick.datepicker' , function( e ){
  e.preventDefault();

  let d = new Date( e.date );

  let v = ( d.getFullYear() + '-' + ( ( d.getMonth() + 1 ).toString().padStart( 2 , '0' ) ) + '-' + ( d.getDate().toString().padStart( 2 , '0' ) ) );

  console.log( v ); 

  /*
  Or:
  $( '#my_date_to_db_input' ).val( v );
  
  Or if, for some reason, you want to set this value to the original datepicker target: 
  $( e.target ).val( v );
  */
 });

EDIT: Also, don't forget to validade before, you know, dumping stuff to the database.

Gataquadrada avatar Feb 03 '19 22:02 Gataquadrada

And if you want the picked date to also go to the original datepicker target, do not call e.preventDefault(); (id. remove the line). In my case I needed to store the timestamp in an hidden <input> but still display the nicely formatted date in the <input> having the datepicker:

The HTML form:

<form id="my-form">
<input type="hidden" name="date_timestamp" />
<input type="text" name="date_pretty" data-timestamp-field-name="date_timestamp" />
</form>

The JavaScript code:

const dateInput = $('#my-form').find('input[name="date_pretty"]');
dateInput.datepicker({
    // (Your usual options for the datepicker here)
});

// Store date as timestamp in a separate hidden input.
// Reference: https://github.com/fengyuanchen/datepicker/issues/161
dateInput.on('pick.datepicker', function(event) {
    const changedDateInput = $(event.target);

    // Get the form
    const form = event.target.form; // Use native JavaScript object here

    // Get the name of the hidden input
    const tsInputName = changedDateInput.data('timestamp-input-name');

    if (tsInputName && form) {
        // Get the hidden input
        const tsInput = $(form).first().find('[name="' + tsInputName + '"]').first();

        if (tsInput) {
            // Get timestamp from picked date
            let ts = Math.floor(event.date.getTime() / 1000);

            // Store timestamp in the hidden input
            tsInput.val(ts);
        }
    }
});

(Note: the hidden input name is given by an HTML attribute data-timestamp-field-name in the input having the datepicker)

C-Duv avatar Nov 29 '21 15:11 C-Duv