Jak sformatować datę JavaScript

Jak sformatować obiekt daty JavaScript, aby wydrukował jako 10-Aug-2010?

Author: Sunil Garg, 2010-08-24

30 answers

Uwaga: poniżej znajdują się lepsze odpowiedzi. Odpowiedź ta została napisana w 2010 roku i od tego czasu pojawiły się nowsze i lepsze rozwiązania. Operacja powinna przyjąć inną odpowiedź.

function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

console.log(formatDate(new Date()));  // show current date-time in console

Możesz edytować tablicę monthNames, Aby użyć Jan, Feb, Mar, itd..

 898
Author: Marko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-13 10:23:50

Użyj toLocaleDateString();

Metoda toLocaleDateString() zwraca łańcuch znaków z wrażliwą na język reprezentacją części daty. Argumenty locales i options pozwalają aplikacjom określić język, którego konwencje formatowania powinny być używane i pozwalają dostosować zachowanie funkcji.

Wartości, które można przekazać w Opcjach dla różnych kluczy:

  1. dzień:
    Reprezentacja dnia.
    Możliwe wartości to " numeryczne", "2-cyfrowy".

  2. Przedstawienie dnia powszedniego.
    Możliwe wartości to "narrow", "short", "long".
  3. rok:
    Reprezentacja roku.
    Możliwe wartości to "numeric", "2-digit".
  4. miesiąc:
    Reprezentacja miesiąca.
    Możliwe wartości to "numeric"," 2-digit"," narrow"," short","long".
  5. godzina:
    Przedstawienie godziny.
    Możliwe wartości to "numeric", "2-digit".
  6. minuta: Minucie.
    Możliwe wartości to "numeric", "2-digit".
  7. drugi:
    Reprezentacja 2.
    Możliwe wartości to "numeryczne", 2-cyfrowe".

Wszystkie te klucze są opcjonalne. Możesz zmienić liczbę wartości opcji w zależności od wymagań, a to będzie również odzwierciedlać obecność każdego terminu daty.

Uwaga: Jeśli chcesz tylko aby skonfigurować opcje zawartości, ale nadal używać bieżących ustawień regionalnych, podanie null dla pierwszego parametru spowoduje błąd. Zamiast tego użyj undefined.

Dla różnych języków:

  1. "en-US": dla angielskiego
  2. "hi-IN": Dla Hindi
  3. "ja-JP": dla japońskiego

Możesz użyć więcej opcji językowych.

Na przykład

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

Możesz również użyć metody toLocaleString() do tego samego cel. Jedyną różnicą jest to, że ta funkcja zapewnia czas, gdy nie przekazujesz żadnych opcji.

// Example
9/17/2016, 1:21:34 PM

Bibliografia:

 1010
Author: ajeet kanojia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-18 13:17:51

Użyj daty .biblioteka formatu :

var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

Zwraca:

Saturday, June 9th, 2007, 5:46:21 PM 

Dateformat = npm

Http://jsfiddle.net/phZr7/1/

 531
Author: RobertPitt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-14 15:38:12

Jeśli chcesz szybko sformatować datę za pomocą zwykłego JavaScript, użyj getDate, getMonth + 1, getFullYear, getHours i getMinutes:

var d = new Date();

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

// 16-5-2015 9:50

Lub, jeśli potrzebujesz, aby było wyściełane zerami:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);

// 16-05-2015 09:50
 348
Author: sebastian.i,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-11 16:25:20

Cóż, chciałem przekonwertować dzisiejszą datę na MySQL przyjazny ciąg daty, taki jak 2012-06-23, i użyć tego ciągu jako parametru w jednym z moich zapytań. Proste rozwiązanie, które znalazłem jest takie:

var today = new Date().toISOString().slice(0, 10);

Należy pamiętać, że powyższe rozwiązanie nie uwzględnia przesunięcia strefy czasowej.

Możesz rozważyć użycie tej funkcji zamiast:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

To da Ci poprawną datę w przypadku, gdy wykonujesz ten kod wokół początku/końca dnia.

 310
Author: simo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-18 15:54:55

Jeśli jesteś już używasz jQuery UI w swoim projekcie możesz to zrobić w ten sposób:

var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));

// formatted will be 'Jul 8, 2014'

Niektóre opcje formatu datepicker do odtwarzania są dostępne tutaj .

 158
Author: Dmitry Pavlov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-21 20:44:11

Funkcja formatowania niestandardowego:

Dla stałych formatów zadanie wykonuje prosta funkcja. Poniższy przykład generuje międzynarodowy format RRRR-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

Format OP można wygenerować następująco:

function dateToYMD(date) {
    var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d = date.getDate();
    var m = strArray[date.getMonth()];
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

Notatka: jednak zwykle nie jest dobrym pomysłem Rozszerzanie standardowych bibliotek JavaScript(np. poprzez dodanie tej funkcji do prototypu Date).

Bardziej zaawansowana funkcja może generować Konfigurowalne wyjście na podstawie parametru format.

Jeśli pisanie funkcji formatowania jest zbyt długie, istnieje wiele bibliotek, wokół których to robi. Niektóre inne odpowiedzi już je wyliczają. Ale rosnące zależności mają również jej przeciwstawność.

Standardowe funkcje formatowania ECMAScript:

Od nowszych wersji ECMAScript, Klasa Date posiada pewne specyficzne funkcje formatowania:

ToDateString : implementacja zależna, Pokaż tylko datę.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"

ToISOString : pokazuje datę i godzinę ISO 8601.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"

ToJSON : Stringifier dla JSON.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"

ToLocaleDateString: zależna od implementacji, data w formacie locale.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"

ToLocaleString: zależny od implementacji, Data i czas w formacie locale.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"

ToLocaleTimeString : zależny od implementacji, czas w formacie locale.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"

ToString: ogólny toString Dla daty.

Http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

Uwaga: z formatowania można wygenerować własne wyjście >

new Date().toISOString().slice(0,10); //return YYYY-MM-DD

Przykłady:

console.log("1) "+  new Date().toDateString());
console.log("2) "+  new Date().toISOString());
console.log("3) "+  new Date().toJSON());
console.log("4) "+  new Date().toLocaleDateString());
console.log("5) "+  new Date().toLocaleString());
console.log("6) "+  new Date().toLocaleTimeString());
console.log("7) "+  new Date().toString());
console.log("8) "+  new Date().toISOString().slice(0,10));
 128
Author: Adrian Maire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-30 20:22:04

Myślę, że możesz po prostu użyć niestandardowej metody Date toLocaleFormat(formatString)

FormatString: ciąg formatujący w tym samym formacie, jakiego oczekuje strftime() Funkcja W C.

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011

Referencje:

 114
Author: Sébastien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-15 08:51:17

Zwykły JavaScript jest najlepszym wyborem dla małych użytkowników.

Z drugiej strony, jeśli potrzebujesz więcej dat rzeczy, MomentJS jest świetnym rozwiązaniem.

Na przykład:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours
 89
Author: Mite Mitreski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-04 22:17:42

W nowoczesnych przeglądarkach (*), możesz po prostu to zrobić:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

Output if executed today (january 24ᵗʰ, 2016):

'24-Jan-2016'

(*) według MDN, "nowoczesne przeglądarki" oznacza Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15 + i Safari nightly build.

 83
Author: John Slegers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-08 14:55:23

Powinieneś spojrzeć na datę.js . Dodaje wiele wygodnych pomocników do pracy z datami, na przykład w Twoim przypadku:

var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));

Pierwsze kroki: http://www.datejs.com/2007/11/27/getting-started-with-datejs/

 47
Author: NiKo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-18 15:53:26

Mogę uzyskać żądany format w jednej linii, bez bibliotek i metod daty, po prostu regex:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

Update: jak zauważył @RobG, wyjście daty.prototyp.toString () jest zależna od implementacji. Dlatego używaj ostrożnie i modyfikuj, jeśli jest to konieczne dla Twoich implementacji, jeśli używasz tego rozwiązania. W moich testach działa to niezawodnie w Ameryce Północnej, gdzie główne przeglądarki (Chrome, Safari, Firefox i IE) zwracają ten sam format ciągów.

 30
Author: JD Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-10 03:28:01

@Sébastien -- alternatywna Obsługa wszystkich przeglądarek

new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');

Dokumentacja: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

 29
Author: user956584,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-02 16:40:54

Użycie szablonu łańcucha znaków ECMAScript Edition 6 (ES6/ES2015):

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

Jeśli chcesz zmienić ograniczniki:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
 23
Author: vdegenne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-07 13:31:51

Oto kod, który właśnie napisałem do obsługi formatowania daty dla projektu, nad którym pracuję. Naśladuje funkcjonalność formatowania daty PHP do moich potrzeb. Nie krępuj się go używać, to tylko rozszerzenie istniejącego już obiektu Date (). To może nie jest najbardziej eleganckie rozwiązanie, ale działa na moje potrzeby.

var d = new Date(); 
d_string = d.format("m/d/Y h:i:s");

/**************************************
 * Date class extension
 * 
 */
    // Provide month names
    Date.prototype.getMonthName = function(){
        var month_names = [
                            'January',
                            'February',
                            'March',
                            'April',
                            'May',
                            'June',
                            'July',
                            'August',
                            'September',
                            'October',
                            'November',
                            'December'
                        ];

        return month_names[this.getMonth()];
    }

    // Provide month abbreviation
    Date.prototype.getMonthAbbr = function(){
        var month_abbrs = [
                            'Jan',
                            'Feb',
                            'Mar',
                            'Apr',
                            'May',
                            'Jun',
                            'Jul',
                            'Aug',
                            'Sep',
                            'Oct',
                            'Nov',
                            'Dec'
                        ];

        return month_abbrs[this.getMonth()];
    }

    // Provide full day of week name
    Date.prototype.getDayFull = function(){
        var days_full = [
                            'Sunday',
                            'Monday',
                            'Tuesday',
                            'Wednesday',
                            'Thursday',
                            'Friday',
                            'Saturday'
                        ];
        return days_full[this.getDay()];
    };

    // Provide full day of week name
    Date.prototype.getDayAbbr = function(){
        var days_abbr = [
                            'Sun',
                            'Mon',
                            'Tue',
                            'Wed',
                            'Thur',
                            'Fri',
                            'Sat'
                        ];
        return days_abbr[this.getDay()];
    };

    // Provide the day of year 1-365
    Date.prototype.getDayOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((this - onejan) / 86400000);
    };

    // Provide the day suffix (st,nd,rd,th)
    Date.prototype.getDaySuffix = function() {
        var d = this.getDate();
        var sfx = ["th","st","nd","rd"];
        var val = d%100;

        return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
    };

    // Provide Week of Year
    Date.prototype.getWeekOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 

    // Provide if it is a leap year or not
    Date.prototype.isLeapYear = function(){
        var yr = this.getFullYear();

        if ((parseInt(yr)%4) == 0){
            if (parseInt(yr)%100 == 0){
                if (parseInt(yr)%400 != 0){
                    return false;
                }
                if (parseInt(yr)%400 == 0){
                    return true;
                }
            }
            if (parseInt(yr)%100 != 0){
                return true;
            }
        }
        if ((parseInt(yr)%4) != 0){
            return false;
        } 
    };

    // Provide Number of Days in a given month
    Date.prototype.getMonthDayCount = function() {
        var month_day_counts = [
                                    31,
                                    this.isLeapYear() ? 29 : 28,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31
                                ];

        return month_day_counts[this.getMonth()];
    } 

    // format provided date into this.format format
    Date.prototype.format = function(dateFormat){
        // break apart format string into array of characters
        dateFormat = dateFormat.split("");

        var date = this.getDate(),
            month = this.getMonth(),
            hours = this.getHours(),
            minutes = this.getMinutes(),
            seconds = this.getSeconds();
        // get all date properties ( based on PHP date object functionality )
        var date_props = {
            d: date < 10 ? '0'+date : date,
            D: this.getDayAbbr(),
            j: this.getDate(),
            l: this.getDayFull(),
            S: this.getDaySuffix(),
            w: this.getDay(),
            z: this.getDayOfYear(),
            W: this.getWeekOfYear(),
            F: this.getMonthName(),
            m: month < 10 ? '0'+(month+1) : month+1,
            M: this.getMonthAbbr(),
            n: month+1,
            t: this.getMonthDayCount(),
            L: this.isLeapYear() ? '1' : '0',
            Y: this.getFullYear(),
            y: this.getFullYear()+''.substring(2,4),
            a: hours > 12 ? 'pm' : 'am',
            A: hours > 12 ? 'PM' : 'AM',
            g: hours % 12 > 0 ? hours % 12 : 12,
            G: hours > 0 ? hours : "12",
            h: hours % 12 > 0 ? hours % 12 : 12,
            H: hours,
            i: minutes < 10 ? '0' + minutes : minutes,
            s: seconds < 10 ? '0' + seconds : seconds           
        };

        // loop through format array of characters and add matching data else add the format character (:,/, etc.)
        var date_string = "";
        for(var i=0;i<dateFormat.length;i++){
            var f = dateFormat[i];
            if(f.match(/[a-zA-Z]/g)){
                date_string += date_props[f] ? date_props[f] : '';
            } else {
                date_string += f;
            }
        }

        return date_string;
    };
/*
 *
 * END - Date class extension
 * 
 ************************************/
 15
Author: jmiraglia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-08 18:15:55

Jeśli używasz jQuery UI w swoim kodzie, istnieje wbudowana funkcja o nazwie formatDate(). Używam go w ten sposób do sformatowania dzisiejszej daty:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);

Możesz zobaczyć wiele innych przykładów formatowania daty w dokumentacji jQuery UI.

 15
Author: webzy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-20 16:08:09

Mamy na to wiele rozwiązań, ale myślę, że najlepszym z nich jest Moment.js. Więc osobiście proponuję użyć chwili.js dla operacji daty i czasu.

console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
 13
Author: Vijay Maheriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-04 22:33:20

Rozwiązanie JavaScript bez użycia zewnętrznych bibliotek:

var now = new Date()
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
var formattedDate = now.getDate()+"-"+months[now.getMonth()]+"-"+now.getFullYear()
alert(formattedDate)
 12
Author: Prasad DLV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-24 10:49:29

Tak zaimplementowałem wtyczki npm

var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];

var Days = [
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"
];

var formatDate = function(dt,format){
  format = format.replace('ss', pad(dt.getSeconds(),2));
  format = format.replace('s', dt.getSeconds());
  format = format.replace('dd', pad(dt.getDate(),2));
  format = format.replace('d', dt.getDate());
  format = format.replace('mm', pad(dt.getMinutes(),2));
  format = format.replace('m', dt.getMinutes());
  format = format.replace('MMMM', monthNames[dt.getMonth()]);
  format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
  format = format.replace('MM', pad(dt.getMonth()+1,2));
  format = format.replace(/M(?![ao])/, dt.getMonth()+1);
  format = format.replace('DD', Days[dt.getDay()]);
  format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
  format = format.replace('yyyy', dt.getFullYear());
  format = format.replace('YYYY', dt.getFullYear());
  format = format.replace('yy', (dt.getFullYear()+"").substring(2));
  format = format.replace('YY', (dt.getFullYear()+"").substring(2));
  format = format.replace('HH', pad(dt.getHours(),2));
  format = format.replace('H', dt.getHours());
  return format;
}

pad = function(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
 12
Author: Amit Kumar Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-23 06:17:19

new Date().toLocaleDateString()

// "3/21/2018"

Więcej dokumentacji na developer.mozilla.org

 12
Author: Kirk Strobeck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-21 17:23:17

Użytecznym i elastycznym sposobem formatowania dat w JavaScript jest Intl.DateTimeFormat:

var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));

Wynik To: "12-Oct-2017"

Formaty daty i czasu można dostosować za pomocą argumentu options.

Obiekt Intl.DateTimeFormat jest konstruktorem obiektów, które umożliwiają formatowanie daty i czasu wrażliwego na język.

Składnia

new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])

Parametry

Locales

Opcjonalnie. Ciąg znaków ze znacznikiem języka BCP 47 lub tablicą takie sznurki. Ogólna forma i interpretacja argumentu locales znajduje się na stronie Intl. Dozwolone są następujące klucze rozszerzenia Unicode:

nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".

Opcje

Opcjonalnie. Obiekt o niektórych lub wszystkich z następujących właściwości:

LocaleMatcher

Algorytm dopasowania lokalnego, którego należy użyć. Możliwe wartości to "lookup" i "best fit"; domyślną wartością jest "best fit". Informacje na temat tej opcji można znaleźć w Intl strona.

Strefa czasowa

Strefa czasowa do użycia. Tylko implementacje wartości muszą rozpoznawać "UTC"; domyślna jest domyślna Strefa czasowa środowiska uruchomieniowego. Implementacje mogą również rozpoznawać nazwy stref czasowych bazy danych IANA, takie jak"Asia/Shanghai", "Asia/Kolkata", "America/New_York".

Hour12

Czy używać czasu 12-godzinnego (w przeciwieństwie do czasu 24-godzinnego). Możliwe wartości to true i false; domyślną wartością jest locale zależny.

FormatMatcher

Algorytm dopasowujący format do użycia. Możliwe wartości to "basic" i "best fit"; domyślną wartością jest "best fit". Informacje na temat korzystania z tej właściwości znajdują się w poniższych akapitach.

Poniższe właściwości opisują składniki daty i czasu, które mają być użyte w sformatowanym wyjściu oraz ich pożądane reprezentacje. Implementacje są wymagane do obsługi co najmniej następujących podzbiorów:

weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute

Implementacje mogą wspierać inne podzbiory i wnioski będą negocjowane w stosunku do wszystkich dostępnych kombinacji reprezentacji podzbiorów, aby znaleźć najlepsze dopasowanie. Do tej negocjacji dostępne są dwa algorytmy wybrane przez właściwość formatMatcher: w pełni określony algorytm "basic" oraz zależny od implementacji algorytm "best fit".

Dzień powszedni

Przedstawienie dnia powszedniego. Możliwe wartości to "narrow", "short", "long".

Era

Reprezentacja era. Możliwe wartości to "narrow", "short", "long".

Rok

Reprezentacja roku. Możliwe wartości to "numeric", "2-digit".

Miesiąc

Reprezentacja miesiąca. Możliwe wartości to "numeric", "2-digit", "narrow", "short", "long".

Dzień

Przedstawienie dnia. Możliwe wartości to "numeric", "2-digit".

Godzina

Przedstawienie godziny. Możliwe wartości są "numeric", "2-digit".

Minute

Reprezentacja minuty. Możliwe wartości to "numeric", "2-digit".

Druga

Reprezentacja drugiego. Możliwe wartości to "numeric", "2-digit".

TimeZoneName

Reprezentacja nazwy strefy czasowej. Możliwe wartości to "short", "long". Domyślna wartość każdej właściwości komponentu date-time jest niezdefiniowana, ale jeśli wszystkie właściwości komponentu są niezdefiniowane, wtedy przyjmuje się, że rok, miesiąc i dzień to "numeric".

Sprawdź Online

Więcej Szczegółów

 10
Author: Iman Bahrampour,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-01 19:15:15
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
 8
Author: zest,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-18 20:22:52

OK , mamy coś o nazwie Intl , co jest bardzo przydatne do formatowania daty w JavaScript:

Twoja data jak poniżej:

var date = '10/8/2010';

I zmieniasz datę używając new Date () jak poniżej:

date = new Date(date);

A teraz możesz sformatować go w dowolny sposób używając listy locales jak poniżej:

date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010" 


date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010" 


date = new Intl.DateTimeFormat('ar-EG').format(date);  // Arabic date format: "٨‏/١٠‏/٢٠١٠"

Jeśli chcesz dokładnie format, o którym wspomniałeś powyżej, możesz zrobić:

date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');

I wynik będzie:

"10-Aug-2010"
Aby uzyskać więcej informacji na temat ECMAScript Internationalization API (Intl), odwiedź stronę tutaj .
 8
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-01 13:34:04

Cukier.js posiada doskonałe rozszerzenia do obiektu Date, w tym Date.metoda format .

Przykłady z dokumentacji:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')
 7
Author: hasen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-18 15:56:55

Hi sprawdź, czy to pomaga w Twoim problemie.

var d = new Date();

var options = {   
    day: 'numeric',
    month: 'long', 
    year: 'numeric'
};

console.log(d.toLocaleDateString('en-ZA', options));

Data znalezienia formatu

 7
Author: Mr Nsubuga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 07:58:41

Dla każdego, kto szuka naprawdę prostego rozwiązania ES6 do kopiowania i wklejania.

const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}` 

// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
 5
Author: Hinrich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-07 15:00:53

Spróbuj tego:

function init(){
    var d = new Date();
    var day = d.getDate();
    var x = d.toDateString().substr(4, 3);
    var year = d.getFullYear();
    document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>
 4
Author: Arjun Nayak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-04 22:28:27

Oto skrypt, który robi dokładnie to, co chcesz

Https://github.com/UziTech/js-date-format

var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
 3
Author: Tony Brix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-15 15:06:30

Jeśli masz ochotę na krótką, czytelną dla człowieka funkcję - można ją łatwo dostosować do własnych potrzeb.

Parametr timeStamp jest milisekundą z roku 1970-jest zwracany przez new Date().getTime() i wiele innych urządzeń...

Ok, zmieniłem zdanie. Dodałem dodatkową funkcję zero padding. Przekleństwa!
 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 }
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
 }
 3
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-23 13:13:55

Jest nowa biblioteka, smarti.to.js , do lokalnego formatowania liczb JavaScript, dat i dat JSON (Microsoft lub ISO8601).

Przykład:

new Date('2015-1-1').to('dd.MM.yy')         // Outputs 01.01.2015
"2015-01-01T10:11:12.123Z".to('dd.MM.yy')   // Outputs 01.01.2015

Istnieją również niestandardowe krótkie wzorce zdefiniowane w pliku lokalizacyjnym (smarti.to. {culture}. js). Example (smarti.to.et-EE.js"): {]}

new Date('2015-1-1').to('d')                // Outputs 1.01.2015

I zdolność multiformatowania:

smarti.format('{0:n2} + {1:n2} = {2:n2}', 1, 2, 3)   // Output: 1,00 + 2,00 = 3,00
 3
Author: Gene R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-04 22:20:45