2012-01-13 20 views
8

Ho una stringa data/ora come 2012-01-13 04:37:20 ma voglio convertirla in dd-mm-yyyy hh:mm, come posso fare questo?Formattazione della data con Javascript

Sto usando il seguente codice ma genera un'eccezione.

var now = "2012-01-13 04:37:20"; 
var dd = now.toLocaleDateString() + " " + now.toLocaleTimeString(); 
alert(dd); 

risposta

8

È possibile eseguire una semplice manipolazione delle stringhe e creare un oggetto data js. Vedere funzione qui sotto, che accetta data in formato hh // aaaa-mm-gg: mm: ss

DEMO qui

function toJSDate (dateTime) { 

var dateTime = dateTime.split(" ");//dateTime[0] = date, dateTime[1] = time 

var date = dateTime[0].split("-"); 
var time = dateTime[1].split(":"); 

//(year, month, day, hours, minutes, seconds, milliseconds) 
return new Date(date[0], date[1], date[2], time[0], time[1], time[2], 0); 

} 
+5

'data [1]' 'dovrebbe essere data [1] - 1' per il corretto output del mese. – Dzhuang

-2

La variabile ora è un oggetto String e toLocaleDateString metodo ha bisogno di un oggetto Date. Vedi w3schools

5

Utilizzare uno semplice manipolazione delle stringhe (come suggerito da @SKS) oppure utilizzare una libreria . Quest'ultimo è più flessibile e consente di modificare facilmente il formato di input o di output. Ad esempio, utilizzando la libreria Globalize.js, si scrive:

var dd = Globalize.parseDate(now, "yyyy-MM-dd HH:mm:ss"); 
dd = Globalize.format(dd, "dd-MM-yyyy HH:mm"); 

Nota, tuttavia, che i formati quali "hh gg-mm-aaaa: mm" sono confuse - non è né un formato standard ISO né localizzato (lingua -dipendente) formato. La libreria Globalize.js consente di utilizzare formati predefiniti dipendenti dalla lingua oltre a formati specificati in modo esplicito.

Si noti che le routine di parsing e di formattazione dell'ora e della data incorporate in JavaScript dipendono dall'implementazione. Usarli significa codice non-portatile. Ad esempio, non è possibile garantire che new Date() accetti il ​​formato che si ha come input, e toLocaleDateString() scriva la data in un formato dipendente dalla lingua, che può essere qualsiasi cosa.

0

La data richiede l'oggetto Date quindi è necessario fornire var d = new Date() qualcosa come quindi per la formattazione vedere il collegamento http://code.google.com/p/datejs/ sarà utile.

3

La migliore gestione lib in JavaScript data-ora è moment.

moment().format('MMMM Do YYYY, h:mm:ss a'); 
4

Se non avete bisogno di tutte le caratteristiche che una libreria come Moment.js fornisce, quindi è possibile utilizzare il mio porto di strftime. È leggero (1,35 KB rispetto a 57,9 KB ridotto rispetto a Moment.js 2.15.0) e offre la maggior parte delle funzionalità di strftime(). utilizzo

/* Port of strftime(). Compatibility notes: 
* 
* %c - formatted string is slightly different 
* %D - not implemented (use "%m/%d/%y" or "%d/%m/%y") 
* %e - space is not added 
* %E - not implemented 
* %h - not implemented (use "%b") 
* %k - space is not added 
* %n - not implemented (use "\n") 
* %O - not implemented 
* %r - not implemented (use "%I:%M:%S %p") 
* %R - not implemented (use "%H:%M") 
* %t - not implemented (use "\t") 
* %T - not implemented (use "%H:%M:%S") 
* %U - not implemented 
* %W - not implemented 
* %+ - not implemented 
* %% - not implemented (use "%") 
* 
* strftime() reference: 
* http://man7.org/linux/man-pages/man3/strftime.3.html 
* 
* Day of year (%j) code based on Joe Orost's answer: 
* http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366 
* 
* Week number (%V) code based on Taco van den Broek's prototype: 
* http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html 
*/ 
function strftime(sFormat, date) { 
    if (!(date instanceof Date)) date = new Date(); 
    var nDay = date.getDay(), 
    nDate = date.getDate(), 
    nMonth = date.getMonth(), 
    nYear = date.getFullYear(), 
    nHour = date.getHours(), 
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], 
    isLeapYear = function() { 
     return (nYear%4===0 && nYear%100!==0) || nYear%400===0; 
    }, 
    getThursday = function() { 
     var target = new Date(date); 
     target.setDate(nDate - ((nDay+6)%7) + 3); 
     return target; 
    }, 
    zeroPad = function(nNum, nPad) { 
     return ('' + (Math.pow(10, nPad) + nNum)).slice(1); 
    }; 
    return sFormat.replace(/%[a-z]/gi, function(sMatch) { 
    return { 
     '%a': aDays[nDay].slice(0,3), 
     '%A': aDays[nDay], 
     '%b': aMonths[nMonth].slice(0,3), 
     '%B': aMonths[nMonth], 
     '%c': date.toUTCString(), 
     '%C': Math.floor(nYear/100), 
     '%d': zeroPad(nDate, 2), 
     '%e': nDate, 
     '%F': date.toISOString().slice(0,10), 
     '%G': getThursday().getFullYear(), 
     '%g': ('' + getThursday().getFullYear()).slice(2), 
     '%H': zeroPad(nHour, 2), 
     '%I': zeroPad((nHour+11)%12 + 1, 2), 
     '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3), 
     '%k': '' + nHour, 
     '%l': (nHour+11)%12 + 1, 
     '%m': zeroPad(nMonth + 1, 2), 
     '%M': zeroPad(date.getMinutes(), 2), 
     '%p': (nHour<12) ? 'AM' : 'PM', 
     '%P': (nHour<12) ? 'am' : 'pm', 
     '%s': Math.round(date.getTime()/1000), 
     '%S': zeroPad(date.getSeconds(), 2), 
     '%u': nDay || 7, 
     '%V': (function() { 
       var target = getThursday(), 
       n1stThu = target.valueOf(); 
       target.setMonth(0, 1); 
       var nJan1 = target.getDay(); 
       if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7); 
       return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2); 
      })(), 
     '%w': '' + nDay, 
     '%x': date.toLocaleDateString(), 
     '%X': date.toLocaleTimeString(), 
     '%y': ('' + nYear).slice(2), 
     '%Y': nYear, 
     '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'), 
     '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1') 
    }[sMatch] || sMatch; 
    }); 
} 

Esempio:

// Returns "15-09-2016 16:20" 
strftime('%d-%m-%Y %H:%M'); 

// You can optionally pass it a Date object 
// Returns "01-01-2016 21:30" 
strftime('%d-%m-%Y %H:%M', new Date('Jan 1, 2016 9:30 PM')); 

L'ultimo codice è disponibile qui: https://github.com/thdoan/strftime

0

una piccola funzione, come segue:

var formatTime = function(time, format){ 
time = typeof time == 'number' ? new Date(time) : time; 
format = format || 'yyyy-mm-dd hh:MM:ss'; 
var year = time.getFullYear(); 
var month = time.getMonth() + 1; 
var date = time.getDate(); 
var hours = time.getHours(); 
var minutes = time.getMinutes(); 
var seconds = time.getSeconds(); 
var add0 = function(t){return t < 10 ? '0' + t : t} 
var replaceMent = { 
    'yyyy': year, 
    'mm': add0(month), 
    'm': month, 
    'dd': add0(date), 
    'd': date, 
    'hh': add0(hours), 
    'h': hours, 
    'MM': add0(minutes), 
    'M': minutes, 
    'ss': add0(seconds), 
    's': seconds 
} 
for(var k in replaceMent){ 
    format = format.replace(k, replaceMent[k]); 
} 
return format; 

}

1

Penso che sia meglio usare la classe Intl.DateTimeFormat.

L'utilizzo è abbastanza semplice.Non puoi inserire un pattern come vuoi, ma ti darà i risultati che desideri.

Ecco un esempio su come usarlo:

public formatDate(date : Date) : string{ 
    var options = { year: 'numeric', month: 'short', day: 'numeric' }; 
    return new Intl.DateTimeFormat('de-DE', options).format(date); 
} 

Se davvero si vuole inserire una stringa DateTimeFormat, sarebbe abbastanza facile scrivere una funzione che analizza la stringa utilizzando Regex, ma io don penso che sia necessario

Per ulteriori informazioni vai qui:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

+0

Buono a sapersi, ma questo non è disponibile su tutte le piattaforme come descritto nel riferimento a mozilla –

0

Per lavorare con DateTimes in JavaScript è meglio utilizzare il 'Intl.DateTimeFormat' come segue:

var date = new Date('2012-01-13 14:37:20'); 
var options = { year: 'numeric', month: '2-digit', day: '2-digit', 
hour:'2-digit', minute: '2-digit',hour12: false}; 
console.log(new Intl.DateTimeFormat('en-US', options).format(date).replace(/\//g,'-').replace(',','')); 

Risultato: "01- 13-2012 14:37 "

I formati di data e ora possono essere personalizzati con l'argomento opzioni.

Check Online

0

facilmente realizzabile il mio pacchetto date-shortcode:

const dateShortcode = require('date-shortcode') 
dateShortcode.parse('{DD-MM-YYYY hh:mm}', '2012-01-13 04:37:20') 
//=> '13-01-2012 04:37' 
Problemi correlati