jQuery UI DatePicker-Cambiar Formato de Fecha


Estoy usando el DatePicker de interfaz de usuario de jQuery UI como selector independiente. Tengo este código:

<div id="datepicker"></div>

Y la siguiente JS:

$('#datepicker').datepicker();

Cuando intento devolver el valor con este código:

var date = $('#datepicker').datepicker('getDate');

Me devuelven esto:

Tue Aug 25 2009 00:00:00 GMT+0100 (BST)

Que es totalmente el formato equivocado. ¿Hay alguna forma de que lo devuelva en el formato DD-MM-YYYY?

Author: Eborbob, 2009-08-25

25 answers

Aquí hay uno específico para su código:

var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val();

Más información general disponible aquí:

 882
Author: AvatarKava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-21 13:34:16

Dentro del código de script de jQuery, simplemente pegue el código.

$( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' });

Esto debería funcionar.

 90
Author: sampath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-11 22:29:11

El getDate método de datepicker devuelve un tipo de fecha, no una cadena.

Necesita formatear el valor devuelto a una cadena usando su formato de fecha. Utilice la función formatDate de datepicker:

var dateTypeVar = $('#datepicker').datepicker('getDate');
$.datepicker.formatDate('dd-mm-yy', dateTypeVar);

La lista completa de especificadores de formato está disponible aquí.

 56
Author: kcsoft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-09 09:20:05

Aquí complete el código para el selector de fecha con formato de fecha (aa/mm/dd).

Copie el enlace de abajo y pegue la etiqueta principal:

   <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>  
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 

   <script type="text/javascript">
       $(function() {
               $("#datepicker").datepicker({ dateFormat: "yy-mm-dd" }).val()
       });
   </script>

Copie el código debajo y pegue entre la etiqueta del cuerpo:

      Date: <input type="text" id="datepicker" size="30"/>    

Si desea dos(2) texto de tipo de entrada como Start Date y End Date, use este script y cambie el formato de fecha.

   <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>  
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 

   <script type="text/javascript">
       $(function() {
               $("#startdate").datepicker({ dateFormat: "dd-mm-yy" }).val()
               $("#enddate").datepicker({ dateFormat: "dd-mm-yy" }).val()
       });

   </script>  

Dos texto de entrada como:

      Start Date: <input type="text" id="startdate" size="30"/>    
      End Date: <input type="text" id="enddate" size="30"/>
 33
Author: Nasirali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-09 09:22:29

getDate la función devuelve una fecha JavaScript. Utilice el siguiente código para formatear esta fecha:

var dateObject = $("#datepicker").datepicker("getDate");
var dateString = $.datepicker.formatDate("dd-mm-yy", dateObject);

Utiliza una función de utilidad que está integrada en datepicker:

$.datepicker.formatDate( format, date, settings ) - Formatee una fecha en un valor de cadena con un formato especificado.

La lista completa de especificadores de formato está disponible aquí.

 18
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-21 09:13:48

DateFormat

El formato para las fechas analizadas y mostradas. Este atributo es uno de los atributos de regionalización. Para una lista completa de los posibles formatos consulte la función formatDate.

Ejemplos de código Inicialice un datepicker con la opción DateFormat indicado.

$( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' });

Obtener o establecer la opción DateFormat, después de init.

//getter
var dateFormat = $( ".selector" ).datepicker( "option", "dateFormat" );
//setter
$( ".selector" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
 17
Author: 2 revs, 2 users 60%user369661,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-09 09:16:43

$("#datepicker").datepicker("getDate") devuelve un objeto date, no una cadena.

var dateObject = $("#datepicker").datepicker("getDate"); // get the date object
var dateString = dateObject.getFullYear() + '-' + (dateObject.getMonth() + 1) + '-' + dateObject.getDate();// Y-n-j in php date() format
 9
Author: Catalin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 09:08:45
<script type="text/javascript">
  $(function() {
    $( "#date" ).datepicker( {minDate: '0', dateFormat: 'yy-dd-mm' } );
  });
</script>
 9
Author: Muddasir Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-06 09:54:33

Intenta usar el

$( ".selector" ).datepicker({ dateFormat: 'dd/mm/yy' });  

Y hay muchas opciones disponibles para el datepicker que puedes encontrar Aquí

http://api.jqueryui.com/datepicker/

Esta es la forma en que llamamos al datepicker con el parámetro

$(function() {
      $('.selector').datepicker({
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            numberOfMonths: 1,
            buttonImage: 'contact/calendar/calendar.gif',
            buttonImageOnly: true,
            onSelect: function(selectedDate) {
                 // we can write code here 
             }
      });
});
 8
Author: Ritesh d joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-07 12:53:36

Simplemente puede usar este formato en su función igual que

     $(function() {  
        $( "#datepicker" ).datepicker({
            dateFormat: 'dd/mm/yy',
          changeMonth: true,
          changeYear: true
        });
      });

<input type="text" id="datepicker"></p>
 7
Author: Rohit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-06 10:17:34

Esto también funciona:

$("#datepicker").datepicker({
    dateFormat:'d-m-yy'
});
 5
Author: Patrick Mutwiri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-11 12:55:29

Si necesita la fecha en formato yy-mm-dd, puede usar esto: -

$("#datepicker").datepicker({ dateFormat: "yy-mm-dd" });

Puede encontrar todo el formato soportado https://jqueryui.com/datepicker/#date-formats

Yo estaba en necesidad de 06,Dic 2015, hice esto: -

$("#datepicker").datepicker({ dateFormat: "d M,y" });
 4
Author: Kgn-web,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-06 09:26:05
$("#datepicker").datepicker({ dateFormat: "yy-mm-dd" }).val()
 3
Author: sad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-11 22:29:01
<script>
    $(function() {  
        $("#datepicker").datepicker(); 
        $('#datepicker').datepicker('option', {dateFormat: 'd MM y'});
    }); 
    $("#startDate").datepicker({dateFormat: 'd MM y'}); 
</script>
 3
Author: Sat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-19 04:34:20

Simplemente ejecute esta página HTML, puede ver varios formatos.

<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Format date</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
    $( "#datepicker" ).datepicker();
    $( "#format" ).change(function() {
        $( "#datepicker" ).datepicker( "option", "dateFormat", $( this ).val() );
    });
});
</script>
</head>
<body>

<p>Date: <input type="text" id="datepicker" size="30" /></p>

<p>Format options:<br />
<select id="format">
    <option value="mm/dd/yy">Default - mm/dd/yy</option>
    <option value="yy-mm-dd">ISO 8601 - yy-mm-dd</option>
    <option value="d M, y">Short - d M, y</option>
    <option value="d MM, y">Medium - d MM, y</option>
    <option value="DD, d MM, yy">Full - DD, d MM, yy</option>
    <option value="'day' d 'of' MM 'in the year' yy">With text - 'day' d 'of' MM 'in the year' yy</option>
</select>
</p>


</body>
</html>
 3
Author: Constant Learner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-17 09:52:48

Si configura un datepicker en un elemento input[type="text"], es posible que no obtenga una fecha con formato consistente, especialmente cuando el usuario no sigue el formato de fecha para la entrada de datos.

Por ejemplo, cuando se establece el formato de datos como dd-mm-yy y el usuario escribe 1-1-1. El datepicker convertirá esto a Jan 01, 2001 internamente, pero llamando a val() en el objeto datepicker devolverá la cadena "1-1-1" exactly exactamente lo que está en el campo de texto.

Esto implica que debe validar la entrada del usuario para asegúrese de que la fecha ingresada esté en el formato que espera o no permita que el usuario ingrese las fechas de forma libre (prefiriendo en su lugar el selector de calendario). Aún así, es posible forzar el código datepicker para que te dé una cadena con el formato que esperas:

var picker = $('#datepicker');

picker.datepicker({ dateFormat: 'dd-mm-yy' });

picker.val( '1-1-1' );  // simulate user input

alert( picker.val() );  // "1-1-1"

var d = picker.datepicker( 'getDate' );
var f = picker.datepicker( 'option', 'dateFormat' );
var v = $.datepicker.formatDate( f, d );

alert( v );             // "01-01-2001"

Tenga en cuenta, sin embargo, que mientras que el método getDate() del datepicker devolverá una fecha, solo puede hacer tanto con la entrada del usuario que no coincida exactamente con el formato de fecha. Esto significa que en ausencia de validación es posible obtener una fecha que es diferente de lo que el usuario espera. Caveat emptor .

 2
Author: par,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-14 18:48:00

Estoy usando jquery para datepicker.Estos jqueries se utilizan para que

<script src="jqueryCalendar/jquery-1.6.2.min.js"></script>
<script src="jqueryCalendar/jquery-ui-1.8.15.custom.min.js"></script>
<link rel="stylesheet" href="jqueryCalendar/jqueryCalendar.css">

Entonces sigues este código,

<script>
     jQuery(function() {
     jQuery( "#date" ).datepicker({ dateFormat: 'dd/mm/yy' });
                });
</script>
 2
Author: Sinsil Mathew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-22 12:09:26

Finalmente obtuve la respuesta para el método de cambio de fecha datepicker:

$('#formatdate').change(function(){
    $('#datpicker').datepicker("option","dateFormat","yy-mm-dd");
});
 1
Author: ravi soni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-08 09:24:26

Yo uso esto:

var strDate = $("#dateTo").datepicker('getDate').format('yyyyMMdd');

Que devuelve una fecha de formato como "20120118" para Jan 18, 2012.

 1
Author: Daniel Morin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-28 04:54:43

El siguiente código podría ayudar a verificar si el formulario tiene más de 1 campo de fecha:

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>jQuery UI Datepicker - Display month &amp; year menus</title>
    <link rel="stylesheet" href="jquery-ui.css" />
    <script src="jquery-1.8.3.js"></script>
    <script src="jquery-ui.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script>
    function pickDate(DateObject){
//      alert(DateObject.name)
       $(function() {
               $("#"+DateObject.name).datepicker({ dateFormat: "dd/mm/yy" }).val()
       });
    }
/*
    $(function() {
        $( "#datepicker" ).datepicker({
            changeMonth: true,
            changeYear: true
        });
    });
*/
    </script>
</head>
<body>

<p>From Date: <input type="text" name="FromDate" id="FromDate" size="9" onfocus="pickDate(this)"/></p>
<p>To Date: <input type="text" name="ToDate" id="ToDate" size="9" onfocus="pickDate(this)" /></p>


</body>
</html>
 1
Author: Chakry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-04 20:15:03

Mi opción se da a continuación:

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});
#ui-datepicker-div {
  font-size: 14px;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
</head>
<body>
<h3>Japanese JQuery UI Datepicker</h3>
<input type="text" id="japaneseCalendar"/>

</body>
</html>
 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-05 04:21:59

Creo que la forma correcta de hacer esto sería algo como esto:

var picker = $('.date-picker');
var date = $.datepicker.formatDate(
    picker.datepicker('option', 'dateFormat'),
    picker.datepicker('getDate'));

De esta manera, asegúrese de que la cadena de formato se defina solo una vez y utilice el mismo formateador para traducir la cadena de formato a la fecha formateada.

 0
Author: naktinis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-17 11:31:38

Aquí hay un fragmento de fecha de prueba futura listo para usar. Firefox usa por defecto jquery ui datepicker. De lo contrario se utiliza datepicker HTML5. Si FF alguna vez soporta HTML5 type = "date" el script simplemente será redundante. No olvide que las tres dependencias son necesarias en la etiqueta head.

<script>
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<!--Form element uses HTML 5 type="date"-->
<div class="form-group row">
    <label for="date" class="col-sm-2 col-form-label"Date</label>
    <div class="col-sm-10">          
       <input type="date" class="form-control" name="date" id="date" placeholder="date">
    </div>
</div>

<!--if the user is using FireFox it          
autoconverts type='date' into type='text'. If the type is text the 
script below will assign the jquery ui datepicker with options-->
<script>
$(function() 
{
  var elem = document.createElement('input');
  elem.setAttribute('type', 'date');

  if ( elem.type === 'text' ) 
  {
    $('#date').datepicker();
    $( "#date" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );     
  }
});
 0
Author: jimshot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-29 02:46:56

Puede agregar y probar de esta manera:

HTML archivo:

<input type="text" id="demoDatepicker"></p>

JavaScript archivo:

$(function() {  
    $("#demoDatepicker").datepicker({
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        constrainInput: false
    });
});
 0
Author: Ashraf.Shk786,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 13:25:28

Debe usar data-date-format="yyyy-mm-dd" en su campo de entrada html y selector de datos iniciales en jQuery al igual que simple

$("#issue_date").datepicker({ 
    dateFormat: "yy-mm-dd",
    changeMonth: true,
    changeYear: true
});
 0
Author: SK Developers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 09:36:06