jQuery formattazione della data


186

Come posso formattare la data usando jQuery. Sto usando il codice qui sotto ma sto ottenendo un errore:

 $("#txtDate").val($.format.date(new Date(), 'dd M yy'));

Si prega di suggerire una soluzione.


1
Errore di runtime di Microsoft JScript: '$ .format' è nullo o no un oggetto
— DotnetSparrow

hai incluso il plugin che include le funzioni di formato?
— zzzzBov

39
Sneaky one liner for yyyy-mm-dd:new Date().toJSON().substring(0,10)
— Mike Causer,

è fformat (doppia f)
— jorrebor

10
AVVERTIMENTO! il codice slick: new Date().toJSON().substring(0,10)funzionava bene, ma restituisce la data come GMT! Dato che siamo indietro di 7 ore rispetto al GMT, stavo ricevendo una data sbagliata dopo le 17:00. Ho appena perso un paio d'ore a trovare la causa / sospiro /. Riferimento
— JayRO-GreyBeard

Risposte:


103

jQuery dateFormat è un plugin separato. Devi caricarlo esplicitamente usando un <script>tag.


10
@Dotnet certo, usando altre funzioni: vedi ad esempio qui
— Pekka

33
@Dotnet se si potesse fare usando jQuery, non ci sarebbe un plug-in jQuery per la formattazione della data, vero?
— Pekka,

1
Non so dire se questo dovrebbe essere uno scherzo o no ... è quasi geniale @pekka. Inoltre, è la risposta giusta.
— jcolebrand,

1
jQuery dateFormat non funziona con jQuery Validate. Né la versione pura di JavaScript.
— Kunal B.

3
È difficile credere che jQuery alla vaniglia non abbia una funzione per formattare una data. Questa domanda ha 5 anni, è ancora così?
— Accusa il

212

aggiungi il plugin dell'interfaccia utente jquery nella tua pagina.

 $("#txtDate").val($.datepicker.formatDate('dd M yy', new Date()));

2
Questa è la risposta che stavo cercando, specialmente da quando sto usando l'interfaccia utente jQuery altrove.
— nzifnab,

C'è un modo per ottenere la data + 2 anni?
— Serjas,

1
var currentDate = new Date (); currentDate.setFullYear (currentDate.getFullYear () + 2);
— Thulasiram,

è un peccato che non supporti la formattazione del tempo = S
— Thomas

4
Ecco il link al documento ufficiale: api.jqueryui.com/datepicker/#utility-formatDate
— Guillaume Husta

101

Un'alternativa sarebbe la semplice funzione js date (), se non si desidera utilizzare il plugin jQuery / jQuery:

per esempio:

var formattedDate = new Date("yourUnformattedOriginalDate");
var d = formattedDate.getDate();
var m =  formattedDate.getMonth();
m += 1;  // JavaScript months are 0-11
var y = formattedDate.getFullYear();

$("#txtDate").val(d + "." + m + "." + y);

vedere: 10 modi per formattare ora e data usando JavaScript

Se vuoi aggiungere zeri iniziali al giorno / mese, questo è un esempio perfetto: Javascript aggiunge gli zeri iniziali fino ad oggi

e se vuoi aggiungere tempo con zeri iniziali, prova questo: getMinutes () 0-9 - come fare con due numeri?


sarà utile aggiungere secondi come ha fatto
— @sein

Questo è valido fino a quando l'utente desidera che la data recente o una data venga inserita Datenell'oggetto. Che ne dici di ottenere la data nello stesso formato ma 6 mesi prima della data di nascita?
— Sanjok Gurung,

31

Ecco una funzione di base che ho appena creato che non richiede alcun plug-in esterno:

$.date = function(dateObject) {
    var d = new Date(dateObject);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }
    var date = day + "/" + month + "/" + year;

    return date;
};

Uso:

$.date(yourDateObject);

Risultato:

dd/mm/yyyy

27

ThulasiRam, preferisco il tuo suggerimento. Funziona bene per me in una sintassi / contesto leggermente diverso:

var dt_to = $.datepicker.formatDate('yy-mm-dd', new Date());

Se decidi di utilizzare Datepicker dall'interfaccia utente di JQuery , assicurati di utilizzare i riferimenti corretti nella sezione <head> del documento:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 

25

Sto usando Moment JS . È molto utile e facile da usare.

var date = moment(); //Get the current date
date.format("YYYY-MM-DD"); //2014-07-10

Concordo con l'utente3812343! Moment JS è fantastico, molto facile da assorbire da parte di coloro che hanno lavorato con la sintassi .NET.
— Dominik Ras,

bisogno in anno mese giorno ora minuto secondi?
— Chaitanya Desai,

15

Spero che questo codice risolva il tuo problema.

var d = new Date();

var curr_day = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();

curr_month++ ; // In js, first month is 0, not 1
year_2d = curr_year.toString().substring(2, 4)

$("#txtDate").val(curr_day + " " + curr_month + " " + year_2d)

8

Se stai usando jquery ui, puoi usarlo come di seguito, puoi specificare il tuo formato data

$.datepicker.formatDate( "D dd-M-yy", new Date()) // Output "Fri 08-Sep-2017"

7

Usa questo:

var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);

1
Nota, questo ti dà una data un mese in passato (a meno che non sia accessibile a gennaio, nel qual caso ti dà '00' per il mese) perché date.getMonth () è un indice a base zero.
— jaybrau,

7

Aggiungi questa funzione alla tua <script></script>e chiama da dove vuoi<script></script>

<script>

function GetNow(){
    var currentdate = new Date(); 
    var datetime = currentdate.getDate() + "-"
            + (currentdate.getMonth()+1)  + "-" 
            + currentdate.getFullYear() + " "  
            + currentdate.getHours() + ":"  
            + currentdate.getMinutes() + ":" 
            + currentdate.getSeconds();
    return datetime;
}

window.alert(GetNow());

</script>

oppure puoi semplicemente usare Jquery che fornisce anche funzionalità di formattazione: -

window.alert(Date.parse(new Date()).toString('yyyy-MM-dd H:i:s'));

Adoro la seconda opzione. Risolve tutti i problemi in una volta sola.


1
Questa seconda opzione mi dà "l'argomento radix deve essere compreso tra 2 e 36 in Number.toString". Si schianta.
— IRGeekSauce

6

Sebbene questa domanda sia stata posta alcuni anni fa, non è più necessario un plug-in jQuery a condizione che il valore della data in questione sia una stringa con formato mm/dd/yyyy(come quando si utilizza un selettore di date);

var birthdateVal = $('#birthdate').val();
//birthdateVal: 11/8/2014

var birthdate = new Date(birthdateVal);
//birthdate: Sat Nov 08 2014 00:00:00 GMT-0500 (Eastern Standard Time)

5

È possibile aggiungere la nuova funzione jQuery utente 'getDate'

JSFiddle: getDate jQuery

Oppure puoi eseguire lo snippet di codice. Premi il pulsante "Esegui snippet di codice" sotto questo post.

// Create user jQuery function 'getDate'
(function( $ ){
   $.fn.getDate = function(format) {

	var gDate		= new Date();
	var mDate		= {
	'S': gDate.getSeconds(),
	'M': gDate.getMinutes(),
	'H': gDate.getHours(),
	'd': gDate.getDate(),
	'm': gDate.getMonth() + 1,
	'y': gDate.getFullYear(),
	}

	// Apply format and add leading zeroes
	return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});

	return getDate(str);
   }; 
})( jQuery );


// Usage: example #1. Write to '#date' div
$('#date').html($().getDate("y-m-d H:M:S"));

// Usage: ex2. Simple clock. Write to '#clock' div
function clock(){
	$('#clock').html($().getDate("H:M:S, m/d/y"))
}
clock();
setInterval(clock, 1000); // One second

// Usage: ex3. Simple clock 2. Write to '#clock2' div
function clock2(){

	var format = 'H:M:S'; // Date format
	var updateInterval = 1000; // 1 second
	var clock2Div	= $('#clock2'); // Get div
	var currentTime	= $().getDate(format); // Get time
	
	clock2Div.html(currentTime); // Write to div
	setTimeout(clock2, updateInterval); // Set timer 1 second
	
}
// Run clock2
clock2();

// Just for fun
// Usage: ex4. Simple clock 3. Write to '#clock3' span

function clock3(){

	var formatHM = 'H:M:'; // Hours, minutes
	var formatS = 'S'; // Seconds
	var updateInterval = 1000; // 1 second
	var clock3SpanHM	= $('#clock3HM'); // Get span HM
	var clock3SpanS	= $('#clock3S'); // Get span S
	var currentHM	= $().getDate(formatHM); // Get time H:M
	var currentS	= $().getDate(formatS); // Get seconds
	
	clock3SpanHM.html(currentHM); // Write to div
	clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span
	setTimeout(clock3, updateInterval); // Set timer 1 second
	
}
// Run clock2
clock3();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<div id="date"></div><br>
<div id="clock"></div><br>
<span id="clock3HM"></span><span id="clock3S"></span>

Godere!


4

Puoi utilizzare questo frammento

$('.datepicker').datepicker({
  changeMonth: true,
  changeYear: true,
  yearRange: '1900:+0',
  defaultDate: '01 JAN 1900',
  buttonImage: "http://www.theplazaclub.com/club/images/calendar/outlook_calendar.gif",
  dateFormat: 'dd/mm/yy',
  onSelect: function() {
    $('#datepicker').val($(this).datepicker({
      dateFormat: 'dd/mm/yy'
    }).val());
  }
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<p>
  selector: <input type="text" class="datepicker">
</p>
<p>
  output: <input type="text" id="datepicker">
</p>


4

Semplicemente possiamo formattare la data come,

var month = date.getMonth() + 1;
var day = date.getDate();
var date1 = (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + date.getFullYear();
$("#txtDate").val($.datepicker.formatDate('dd/mm/yy', new Date(date1)));

Dove "data" è una data in qualsiasi formato.



1

Utilizzare l'opzione dateFormat durante la creazione del selettore di date.

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

1

puoi usare il codice qui sotto senza il plugin.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$( function() {
    //call the function on page load
	$( "#datepicker" ).datepicker();
    //set the date format here
    $( "#datepicker" ).datepicker("option" , "dateFormat", "dd-mm-yy");
	
    // you also can use 
    // yy-mm-dd
    // d M, y
    // d MM, y
    // DD, d MM, yy
    // &apos;day&apos; d &apos;of&apos; MM &apos;in the year&apos; yy (With text - 'day' d 'of' MM 'in the year' yy)
	} );
 </script>

Pick the Date: <input type="text" id="datepicker">


1

Questo ha funzionato per me con lievi modifiche e senza alcun plug-in

Ingresso: mer 11 aprile 2018 00:00:00 GMT + 0000

$.date = function(orginaldate) { 
    var date = new Date(orginaldate);
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }
    var date =  month + "/" + day + "/" + year; 
    return date;
};

$.date('Wed Apr 11 2018 00:00:00 GMT+0000')

Uscita: 04/11/2018


0

Non sono del tutto sicuro di poter rispondere a una domanda che è stata posta 2 anni fa, poiché questa è la mia prima risposta su StackOverflow, ma ecco la mia soluzione;

Se una volta hai recuperato la data dal tuo database MySQL, suddividila e quindi utilizza i valori divisi.

$(document).ready(function () {
    var datefrommysql = $('.date-from-mysql').attr("date");
    var arraydate = datefrommysql.split('.');
    var yearfirstdigit = arraydate[2][2];
    var yearlastdigit = arraydate[2][3];
    var day = arraydate[0];
    var month = arraydate[1];
    $('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);
});

Ecco un violino .


0

Ecco l'esempio di codice completo che ho mostrato sul browser, spero che ti sia utile, grazie.

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>jQuery UI Datepicker functionality</title>
      <link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      <!-- Javascript -->
      <script>
         $(function() {
            $( "#datepicker" ).datepicker({
                minDate: -100,
                maxDate: "+0D",
                dateFormat: 'yy-dd-mm',
                onSelect: function(datetext){
                    $(this).val(datetext);
                },
            });
         });
      </script>
   </head>
   <body>
      <!-- HTML --> 
      <p>Enter Date: <input type="text" id="datepicker"></p>
   </body>
</html>


-1

puoi usare questa codifica

$('[name="tgllahir"]').val($.datepicker.formatDate('dd-mm-yy', new Date(data.tgllahir)));

2
Le risposte di solo codice sono sconsigliate perché non spiegano come risolvono il problema. Aggiorna la tua risposta per spiegare come questo migliora su molte altre risposte accettate e votate che questa domanda ha già. Inoltre, questa domanda ha 6 anni, i tuoi sforzi sarebbero più apprezzati dagli utenti che hanno recenti domande senza risposta. Per favore, leggi Come posso scrivere una buona risposta .
— FluffyKitten,

1
La risposta non menzionava la richiesta dell'interfaccia utente di jQuery
— sean2078,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.