Format daty JavaScript jako RRRR-mm-dd

Mam datę w formacie Sun May 11,2014. Jak mogę przekonwertować go do {[2] } za pomocą JavaScript?

function taskDate(dateMilli) {
    var d = (new Date(dateMilli) + '').split(' ');
    d[2] = d[2] + ',';

    return [d[0], d[1], d[2], d[3]].join(' ');
}

var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));

Powyższy kod daje mi ten sam format daty, sun may 11,2014. Jak mogę to naprawić?

Author: Kamil Kiełczewski, 2014-05-11

30 answers

Możesz zrobić:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}
 
console.log(formatDate('Sun May 11,2014'));

Przykład użycia:

console.log(formatDate('Sun May 11,2014'));

Wyjście:

2014-05-11

Demo na JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/

 683
Author: user3470953,
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
2021-02-13 22:03:31

Po prostu wykorzystaj wbudowaną metodę toISOString, która przenosi datę do formatu ISO 8601:

yourDate.toISOString().split('T')[0]

Gdzie yourDate jest obiektem daty.

Edytuj: @exbuddha napisał to do obsługi strefy czasowej w komentarze :

const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
 655
Author: Darth Egregious,
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
2020-09-30 10:26:28

Używam tego sposobu, aby uzyskać datę w formacie RRRR-mm-dd:)

var todayDate = new Date().toISOString().slice(0,10);
 191
Author: Fernando Aguilar,
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-07-01 15:11:42

Najprostszym sposobem na przekonwertowanie daty do formatu RRRR-mm-dd jest wykonanie tego:

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

Jak to działa:

  • new Date("Sun May 11,2014") konwertuje łańcuch znaków "Sun May 11,2014" Na obiekt date, który reprezentuje czas Sun May 11 2014 00:00:00 w strefie czasowej w oparciu o bieżące ustawienia regionalne (Ustawienia systemu hosta)
  • new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) Konwertuje datę na obiekt daty odpowiadający czasowi Sun May 11 2014 00:00:00 W UTC (czas standardowy), odejmując przesunięcie strefy czasowej
  • .toISOString() konwertuje obiekt date NA ISO 8601 string 2014-05-11T00:00:00.000Z
  • .split("T") dzieli łańcuch na tablicę ["2014-05-11", "00:00:00.000Z"]
  • [0] pobiera pierwszy element tej tablicy

Demo

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

console.log(dateString);
 148
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
2019-09-07 12:59:20

2020 odpowiedź

Możesz użyć natywnej funkcji .toLocaleDateString(), która obsługuje kilka użytecznych param, takich jak locale (aby wybrać format jak MM/DD/RRRR lub RRRR/MM/DD), Strefa czasowa (Aby przekonwertować datę) i opcje szczegółów formatów (np: 1 vs 01 vs styczeń).

Przykłady

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

Zauważ, że czasami aby wypisać datę w określonym formacie pożądania, musisz znaleźć kompatybilne ustawienia regionalne z tym formatem. Możesz znaleźć przykładowe lokalizacje tutaj: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

Zwróć uwagę, że locale po prostu zmień format, jeśli chcesz przekształcić określoną datę na równoważnik czasu określonego kraju lub miasta, musisz użyć param timezone .

 77
Author: Juanma Menendez,
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
2020-10-06 16:46:47
format = function date2str(x, y) {
    var z = {
        M: x.getMonth() + 1,
        d: x.getDate(),
        h: x.getHours(),
        m: x.getMinutes(),
        s: x.getSeconds()
    };
    y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
        return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
    });

    return y.replace(/(y+)/g, function(v) {
        return x.getFullYear().toString().slice(-v.length)
    });
}

Wynik:

format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
 44
Author: orangleliu,
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
2021-01-04 22:51:14

Kombinacja niektórych odpowiedzi:

var d = new Date(date);
date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2)
].join('-');
 42
Author: aqwsez,
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-15 13:10:43

Jeśli nie masz nic przeciwko używaniu bibliotek, możesz po prostu użyć momentów.biblioteka js Jak Tak:

var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');

var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
 34
Author: Nifemi Sola-Ojo,
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
2019-09-07 13:01:00

Możesz użyć toLocaleDateString('fr-CA') na Date obiekcie

console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));

Również dowiedziałem się, że te lokalizacje dają właściwy wynik z tej listy lokalizacyjnej Lista wszystkich Locale i ich krótkie kody?

'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'

var localesList = ["af-ZA",
  "am-ET",
  "ar-AE",
  "ar-BH",
  "ar-DZ",
  "ar-EG",
  "ar-IQ",
  "ar-JO",
  "ar-KW",
  "ar-LB",
  "ar-LY",
  "ar-MA",
  "arn-CL",
  "ar-OM",
  "ar-QA",
  "ar-SA",
  "ar-SY",
  "ar-TN",
  "ar-YE",
  "as-IN",
  "az-Cyrl-AZ",
  "az-Latn-AZ",
  "ba-RU",
  "be-BY",
  "bg-BG",
  "bn-BD",
  "bn-IN",
  "bo-CN",
  "br-FR",
  "bs-Cyrl-BA",
  "bs-Latn-BA",
  "ca-ES",
  "co-FR",
  "cs-CZ",
  "cy-GB",
  "da-DK",
  "de-AT",
  "de-CH",
  "de-DE",
  "de-LI",
  "de-LU",
  "dsb-DE",
  "dv-MV",
  "el-GR",
  "en-029",
  "en-AU",
  "en-BZ",
  "en-CA",
  "en-GB",
  "en-IE",
  "en-IN",
  "en-JM",
  "en-MY",
  "en-NZ",
  "en-PH",
  "en-SG",
  "en-TT",
  "en-US",
  "en-ZA",
  "en-ZW",
  "es-AR",
  "es-BO",
  "es-CL",
  "es-CO",
  "es-CR",
  "es-DO",
  "es-EC",
  "es-ES",
  "es-GT",
  "es-HN",
  "es-MX",
  "es-NI",
  "es-PA",
  "es-PE",
  "es-PR",
  "es-PY",
  "es-SV",
  "es-US",
  "es-UY",
  "es-VE",
  "et-EE",
  "eu-ES",
  "fa-IR",
  "fi-FI",
  "fil-PH",
  "fo-FO",
  "fr-BE",
  "fr-CA",
  "fr-CH",
  "fr-FR",
  "fr-LU",
  "fr-MC",
  "fy-NL",
  "ga-IE",
  "gd-GB",
  "gl-ES",
  "gsw-FR",
  "gu-IN",
  "ha-Latn-NG",
  "he-IL",
  "hi-IN",
  "hr-BA",
  "hr-HR",
  "hsb-DE",
  "hu-HU",
  "hy-AM",
  "id-ID",
  "ig-NG",
  "ii-CN",
  "is-IS",
  "it-CH",
  "it-IT",
  "iu-Cans-CA",
  "iu-Latn-CA",
  "ja-JP",
  "ka-GE",
  "kk-KZ",
  "kl-GL",
  "km-KH",
  "kn-IN",
  "kok-IN",
  "ko-KR",
  "ky-KG",
  "lb-LU",
  "lo-LA",
  "lt-LT",
  "lv-LV",
  "mi-NZ",
  "mk-MK",
  "ml-IN",
  "mn-MN",
  "mn-Mong-CN",
  "moh-CA",
  "mr-IN",
  "ms-BN",
  "ms-MY",
  "mt-MT",
  "nb-NO",
  "ne-NP",
  "nl-BE",
  "nl-NL",
  "nn-NO",
  "nso-ZA",
  "oc-FR",
  "or-IN",
  "pa-IN",
  "pl-PL",
  "prs-AF",
  "ps-AF",
  "pt-BR",
  "pt-PT",
  "qut-GT",
  "quz-BO",
  "quz-EC",
  "quz-PE",
  "rm-CH",
  "ro-RO",
  "ru-RU",
  "rw-RW",
  "sah-RU",
  "sa-IN",
  "se-FI",
  "se-NO",
  "se-SE",
  "si-LK",
  "sk-SK",
  "sl-SI",
  "sma-NO",
  "sma-SE",
  "smj-NO",
  "smj-SE",
  "smn-FI",
  "sms-FI",
  "sq-AL",
  "sr-Cyrl-BA",
  "sr-Cyrl-CS",
  "sr-Cyrl-ME",
  "sr-Cyrl-RS",
  "sr-Latn-BA",
  "sr-Latn-CS",
  "sr-Latn-ME",
  "sr-Latn-RS",
  "sv-FI",
  "sv-SE",
  "sw-KE",
  "syr-SY",
  "ta-IN",
  "te-IN",
  "tg-Cyrl-TJ",
  "th-TH",
  "tk-TM",
  "tn-ZA",
  "tr-TR",
  "tt-RU",
  "tzm-Latn-DZ",
  "ug-CN",
  "uk-UA",
  "ur-PK",
  "uz-Cyrl-UZ",
  "uz-Latn-UZ",
  "vi-VN",
  "wo-SN",
  "xh-ZA",
  "yo-NG",
  "zh-CN",
  "zh-HK",
  "zh-MO",
  "zh-SG",
  "zh-TW",
  "zu-ZA"
];

localesList.forEach(lcl => {
  if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
    console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
  }
});
 22
Author: Aleksandr Belugin,
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
2020-02-01 00:33:53

Po prostu użyj tego:

var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

Proste i słodkie;)

 17
Author: Pardeep Jain,
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
2019-09-07 13:44:04

toISOString() zakłada, że data jest czasem lokalnym i konwertuje ją na UTC. Otrzymasz nieprawidłowy ciąg daty.

Poniższa metoda powinna zwrócić to, czego potrzebujesz.

Date.prototype.yyyymmdd = function() {         

    var yyyy = this.getFullYear().toString();                                    
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
    var dd  = this.getDate().toString();             

    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Źródło: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

 12
Author: user1920925,
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
2019-09-07 13:48:58

Pobieraj Rok, Miesiąc i dzień, a następnie łącz je razem. Prosto, prosto i dokładnie.

function formatDate(date) {
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 101).toString().substring(1);
    var day = (date.getDate() + 100).toString().substring(1);
    return year + "-" + month + "-" + day;
}

//Usage example:
alert(formatDate(new Date()));
 12
Author: Luo Jiong Hui,
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
2020-01-20 15:15:50

Najkrótsza

.toJSON().slice(0,10);

var d = new Date('Sun May 11,2014' +' UTC');   // Parse as UTC
let str = d.toJSON().slice(0,10);              // Show as UTC

console.log(str);
 12
Author: Kamil Kiełczewski,
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
2020-08-26 08:30:11

Sugeruję użycie czegoś w rodzaju formatDate-js zamiast próbować go replikować za każdym razem. Wystarczy użyć biblioteki, która obsługuje wszystkie główne akcje strftime.

new Date().format("%Y-%m-%d")
 6
Author: Michael Baldry,
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
2019-09-07 12:47:23

Aby wziąć pod uwagę również strefę czasową, ta jednowierszowa powinna być dobra bez żadnej biblioteki:

new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
 6
Author: krsoni,
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
2019-09-07 13:01:45

Możesz spróbować tego: https://www.npmjs.com/package/timesolver

npm i timesolver

Użyj go w kodzie:

const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");

Można uzyskać ciąg daty za pomocą tej metody:

getString
 6
Author: sean1093,
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
2019-09-07 13:41:40

Gdy ES2018 kręci się wokół (działa w chrome), możesz po prostu powtórzyć to

(new Date())
    .toISOString()
    .replace(
        /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
        '$<year>-$<month>-$<day>'
    )

2020-07-14

Lub jeśli chcesz coś dość uniwersalnego z żadnych bibliotek

(new Date())
    .toISOString()
    .match(
        /^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
    )
    .groups

Co skutkuje wyodrębnieniem następujących

{
    H: "8"
    HH: "08"
    M: "45"
    MM: "45"
    S: "42"
    SS: "42"
    SSS: "42.855"
    d: "14"
    dd: "14"
    m: "7"
    mm: "07"
    timezone: "Z"
    yy: "20"
    yyyy: "2020"
}

Które możesz użyć tak z replace(..., '$<d>/$<m>/\'$<yy> @ $<H>:$<MM>') Jak na górze zamiast .match(...).groups aby uzyskać

14/7/'20 @ 8:45
 5
Author: Hashbrown,
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
2020-07-14 08:49:40
const formatDate = d => [
    d.getFullYear(),
    (d.getMonth() + 1).toString().padStart(2, '0'),
    d.getDate().toString().padStart(2, '0')
].join('-');
Możesz użyć padstart.

PadStart (N, '0') zapewnia, że minimum n znaków jest w łańcuchu i poprzedza go znakiem '0' aż do osiągnięcia tej długości.

Join (' - ') łączy tablicę, dodając symbol ' - ' między każdym elementem.

GetMonth () zaczyna się od 0, stąd +1.

 5
Author: Ado Ren,
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
2020-10-06 07:17:54

Data.js jest do tego świetny.

require("datejs")
(new Date()).toString("yyyy-MM-dd")
 4
Author: Tan Wang,
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-10-20 05:56:46

Żadna z tych odpowiedzi mnie nie zadowoliła. Chciałem wieloplatformowego rozwiązania, które dało mi dzień w lokalnej strefie czasowej bez korzystania z zewnętrznych bibliotek.

Oto co wymyśliłem:

function localDay(time) {
  var minutesOffset = time.getTimezoneOffset()
  var millisecondsOffset = minutesOffset*60*1000
  var local = new Date(time - millisecondsOffset)
  return local.toISOString().substr(0, 10)
}

Należy zwrócić dzień daty, w formacie RRRR-MM-DD, w strefie czasowej odniesienia do daty.

Więc na przykład, localDay(new Date("2017-08-24T03:29:22.099Z")) zwróci "2017-08-23", mimo że jest już 24.godzina UTC.

Musiszpolyfill Data.prototyp.toISOString for it to działa w Internet Explorer 8, ale powinien być obsługiwany wszędzie indziej.

 4
Author: Erik Pukinskis,
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
2019-09-07 12:52:09
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

Lub

new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Spróbuj tego!
 4
Author: Williaan Lopes,
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
2020-04-29 03:36:09

Jeśli używasz momentjs, teraz zawierają stałą dla tego formatu YYYY-MM-DD:

date.format(moment.HTML5_FMT.DATE)
 3
Author: Stefan Zhelyazkov,
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
2020-05-21 11:09:59

Jest jeden sposób, aby to zrobić:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));
 2
Author: Gergo Erdosi,
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-05-11 13:29:13

Kilka z poprzednich odpowiedzi było OK, ale nie były zbyt elastyczne. Chciałem czegoś, co naprawdę poradzi sobie z większą liczbą przypadków edge, więc wziąłem odpowiedź @ orangleliu i rozszerzyłem ją. https://jsfiddle.net/8904cmLd/1/

function DateToString(inDate, formatString) {
    // Written by m1m1k 2018-04-05

    // Validate that we're working with a date
    if(!isValidDate(inDate))
    {
        inDate = new Date(inDate);
    }

    // See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
    //formatString = CountryCodeToDateFormat(formatString);

    var dateObject = {
        M: inDate.getMonth() + 1,
        d: inDate.getDate(),
        D: inDate.getDate(),
        h: inDate.getHours(),
        m: inDate.getMinutes(),
        s: inDate.getSeconds(),
        y: inDate.getFullYear(),
        Y: inDate.getFullYear()
    };

    // Build Regex Dynamically based on the list above.
    // It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
    var dateMatchRegex = joinObj(dateObject, "+|") + "+";
    var regEx = new RegExp(dateMatchRegex,"g");
    formatString = formatString.replace(regEx, function(formatToken) {
        var datePartValue = dateObject[formatToken.slice(-1)];
        var tokenLength = formatToken.length;

        // A conflict exists between specifying 'd' for no zero pad -> expand
        // to '10' and specifying yy for just two year digits '01' instead
        // of '2001'.  One expands, the other contracts.
        //
        // So Constrict Years but Expand All Else
        if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
        {
            // Expand single digit format token 'd' to
            // multi digit value '10' when needed
            var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
        }
        var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
        return (zeroPad + datePartValue).slice(-tokenLength);
    });

    return formatString;
}

Przykładowe użycie:

DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
 2
Author: m1m1k,
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
2019-09-07 12:58:19

Formatowanie ciągu daty jest dość proste, np.

var s = 'Sun May 11,2014';

function reformatDate(s) {
  function z(n){return ('0' + n).slice(-2)}
  var months = [,'jan','feb','mar','apr','may','jun',
                 'jul','aug','sep','oct','nov','dec'];
  var b = s.split(/\W+/);
  return b[3] + '-' +
    z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
    z(b[2]);
}

console.log(reformatDate(s));
 2
Author: RobG,
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
2019-09-07 13:48:17

function myYmd(D){
    var pad = function(num) {
        var s = '0' + num;
        return s.substr(s.length - 2);
    }
    var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());
    return Result;
}

var datemilli = new Date('Sun May 11,2014');
document.write(myYmd(datemilli));
 1
Author: Andrei,
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-12-19 08:38:04

var d = new Date("Sun May 1,2014");

var year  = d.getFullYear();
var month = d.getMonth() + 1;
var day   = d.getDate(); 

month = checkZero(month);             
day   = checkZero(day);

var date = "";

date += year;
date += "-";
date += month;
date += "-";
date += day;

document.querySelector("#display").innerHTML = date;
    
function checkZero(i) 
{
    if (i < 10) 
    {
        i = "0" + i
    };  // add zero in front of numbers < 10

    return i;
}
<div id="display"></div>
 1
Author: antelove,
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
2019-01-06 10:24:04
new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                 (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
 1
Author: Lin,
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
2019-03-01 05:39:55

Udało mi się uzyskać aktualną datę w żądanym formacie (YYYYMMDD HH: MM: SS):

var d = new Date();

var date1 = d.getFullYear() + '' +
            ((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
            '' +
            (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());

var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
            ':' +
            (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
            ':' +
            (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());

print(date1+' '+time1);
 1
Author: SaP,
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
2019-09-07 13:07:55

Nie jest potrzebna biblioteka

Po prostu czysty JavaScript.

Poniższy przykład pobiera ostatnie dwa miesiące od dzisiaj:

var d = new Date()
d.setMonth(d.getMonth() - 2);
var dateString = new Date(d);
console.log('Before Format', dateString, 'After format', dateString.toISOString().slice(0,10))
 1
Author: Panayiotis Georgiou,
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
2019-09-07 13:13:07