Jak uzyskać miesiąc i datę JavaScript w formacie dwucyfrowym?


Odpowiedzi:


811
("0" + this.getDate()).slice(-2)

na datę i podobne:

("0" + (this.getMonth() + 1)).slice(-2)

na miesiąc.


86
Fajnie, ale: function addZ(n){return n<10? '0'+n:''+n;}jest nieco bardziej ogólny.
RobG

9
kromka jest sprytna, ale jest znacznie wolniejsza niż proste porównanie: jsperf.com/slice-vs-comparison
dak

30
@dak: A kiedy to realistycznie będzie miało znaczenie? Wątpię, czy obliczasz miesiąc tysiące razy na sekundę.
Sasha Chedygov

2
@ KasperHoldum– getMonthi getDatezwracają liczby, a nie ciągi znaków. A jeśli wymagana jest kompatybilność z ciągami, '0' + Number(n)wykona to zadanie.
RobG

9
@Sasha Chedygov na pewno możesz obliczyć miesiąc tysiące razy na sekundę, szczególnie jeśli sortujesz
Dexygen

87

Jeśli potrzebujesz formatu „RRRR-MM-DDTHH: mm: ss”, może to być szybsze:

var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ

Lub powszechnie używany format daty i godziny MySQL „RRRR-MM-DD GG: mm: ss”:

var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');

mam nadzieję, że to pomoże


1
To najkrótsze rozwiązanie, z jakim się spotkałem. Jedynym problemem jest przesunięcie strefy czasowej.
Praym

3
Przesunięcie strefy czasowej można rozwiązać za pomocą: var date = new Date (new Date (). GetTime () - new Date (). GetTimezoneOffset () * 60 * 1000) .toISOString (). Substr (0,19) .replace („T”, „”);
Praym

Praym, twój kod działa dla mnie, ale kopiowanie i wklejanie musiało mieć jakiś ukryty znak lub coś, więc po prostu wpisałem go ręcznie.
spacebread

Skończyłem na tym pytaniu, próbując rozwiązać dokładnie ten problem, więc, jak się okazuje, potrzebowałem twojej odpowiedzi.
Inżynier Toast

Pamiętaj, że ta metoda zwróci datę i godzinę zgodnie ze strefą czasową UTC.
Amr

41

Przykład dla miesiąca:

function getMonth(date) {
  var month = date.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}  

Możesz także rozszerzyć Dateobiekt za pomocą takiej funkcji:

Date.prototype.getMonthFormatted = function() {
  var month = this.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}

4
Zauważ, że getMonth zwraca liczbę pomiędzy 0 a 11, a nie 1 i 12.
Salman A

4
Zwraca to niespójne wyniki. W listopadzie i grudniu zwraca ciąg znaków, a przez pozostałe miesiące zwraca liczbę.
Tim Down

Zaktualizowałem kod, aby zaimplementować Salmana Ostrzeżenie, że getMonth ma wartość zero, a nie 1. I dodałem cudzysłowy, aby upewnić się, że ciąg jest zawsze zwracany.
Jan Derk

23

Najlepszym sposobem na to jest utworzenie własnego prostego formatyzatora (jak poniżej):

getDate()zwraca dzień miesiąca (od 1-31)
getMonth()zwraca miesiąc (od 0-11) <od zera, 0 = styczeń, 11 = grudzień
getFullYear() zwraca rok (cztery cyfry) < nie używajgetYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}

20

Dlaczego nie użyć padStart?

var dt = new Date();

year  = dt.getYear() + 1900;
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day   = dt.getDate().toString().padStart(2, "0");

console.log(year + '/' + month + '/' + day);

To zawsze zwraca liczby dwucyfrowe, nawet jeśli miesiąc lub dzień jest krótszy niż 10.

Uwagi:

  • Działa to tylko z Internet Explorerem, jeśli kod js jest transpilowany za pomocą babel .
  • getYear()zwraca rok od 1900 i nie wymaga padStart.
  • getMonth() zwraca miesiąc od 0 do 11.
    • 1 dodaje się do miesiąca przed wypełnieniem, aby zachować od 1 do 12
  • getDate() zwraca dzień od 1 do 31.
    • siódmy dzień powróci, 07więc nie musimy dodawać 1 przed uzupełnieniem łańcucha.

1
Tak. Jest to zawarte w powyższym linku MDN. Jeśli używasz Babel do transponowania, nie powinieneś mieć problemu.
SomeGuyOnAComputer

9

Poniższe dane służą do konwersji formatu daty db2, tj. RRRR-MM-DD przy użyciu operatora trójskładnikowego

var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);  
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate; 
alert(createdDateTo);

7

Zrobiłbym to:

var d = new Date('January 13, 2000');
var s = d.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
console.log(s); // prints 01/13/2000


6
function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}

6

Kolejny przykład, prawie jedna wkładka.

var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );


5
function monthFormated() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

5

Jeśli to może trochę potrwać, chciałem uzyskać:

YYYYMMDD

na dziś i dogadaliśmy się z:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');

2
Odpowiedź jest zgrabna. Dla DD/MM/YYposzedłemnew Date().toISOString().substr(0, 10).split('-').reverse().map(x => x.substr(0, 2)).join('/')
Max Ma

4

To było moje rozwiązanie:

function leadingZero(value) {
  if (value < 10) {
    return "0" + value.toString();
  }
  return value.toString();
}

var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;


3

Nie odpowiedź, ale oto, w jaki sposób otrzymuję wymagany format daty w zmiennej

function setDateZero(date){
  return date < 10 ? '0' + date : date;
}

var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);

Mam nadzieję że to pomoże!


2

Wskazówka z MDN :

function date_locale(thisDate, locale) {
  if (locale == undefined)
    locale = 'fr-FR';
  // set your default country above (yes, I'm french !)
  // then the default format is "dd/mm/YYY"

  if (thisDate == undefined) {
    var d = new Date();
  } else {
    var d = new Date(thisDate);
  }
  return d.toLocaleDateString(locale);
}

var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);

http://jsfiddle.net/v4qcf5x6/


2

new Date().getMonth() Metoda zwraca miesiąc jako liczbę (0-11)

Za pomocą tej funkcji można łatwo uzyskać prawidłowy numer miesiąca.

function monthFormatted() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

1
function GetDateAndTime(dt) {
  var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());

  for(var i=0;i<arr.length;i++) {
    if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
  }

  return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5]; 
}

1

I kolejna wersja tutaj https://jsfiddle.net/ivos/zcLxo8oy/1/ , mam nadzieję, że się przyda.

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")

1

Odpowiedzi tutaj były pomocne, ale potrzebuję więcej: nie tylko miesiąca, daty, miesiąca, godzin i sekund, aby uzyskać domyślną nazwę.

Co ciekawe, chociaż dla wszystkich powyżej konieczne było wstawienie „0”, „+ 1” było potrzebne tylko przez miesiąc, a nie inne.

Jako przykład:

("0" + (d.getMonth() + 1)).slice(-2)     // Note: +1 is needed
("0" + (d.getHours())).slice(-2)         // Note: +1 is not needed

0

Moje rozwiązanie:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

Stosowanie:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http://jsfiddle.net/8xy4Q/1/


0
var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))

0

jeśli chcesz, aby funkcja getDate () zwróciła datę jako 01 zamiast 1, oto jej kod .... Załóżmy, że dzisiejsza data to 01-11-2018

var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();      
console.log(today);       //Output: 2018-11-1


today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today);        //Output: 2018-11-01

0

Chciałem zrobić coś takiego i właśnie to zrobiłem

ps wiem, że na górze są poprawne odpowiedzi, ale chciałem tutaj dodać coś własnego

const todayIs = async () =>{
    const now = new Date();
    var today = now.getFullYear()+'-';
    if(now.getMonth() < 10)
        today += '0'+now.getMonth()+'-';
    else
        today += now.getMonth()+'-';
    if(now.getDay() < 10)
        today += '0'+now.getDay();
    else
        today += now.getDay();
    return today;
}

za dużo wysiłku. Czyż nie
ahmednawazbutt

0

Jeśli zaznaczysz mniej niż 10 , nie musisz dla tego tworzyć nowej funkcji. Po prostu przypisz zmienną do nawiasów i zwróć ją za pomocą operatora trójskładnikowego.

(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`

0
currentDate(){
        var today = new Date();
        var dateTime =  today.getFullYear()+'-'+
                        ((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
                        (today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
                        (today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
                        (today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
                        (today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());        
            return dateTime;
},

0

Sugeruję użycie innej biblioteki o nazwie Moment https://momentjs.com/

W ten sposób możesz bezpośrednio sformatować datę bez dodatkowej pracy

const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'

Pamiętaj, aby zaimportować moment, aby móc go użyć.

yarn add moment 
# to add the dependency
import moment from 'moment' 
// import this at the top of the file you want to use it in

Mam nadzieję, że to pomoże: D


1
Moment.js został już zasugerowany; ale twoja rada jest nadal kompletna i przydatna.
iND

0
$("body").delegate("select[name='package_title']", "change", function() {

    var price = $(this).find(':selected').attr('data-price');
    var dadaday = $(this).find(':selected').attr('data-days');
    var today = new Date();
    var endDate = new Date();
    endDate.setDate(today.getDate()+parseInt(dadaday));
    var day = ("0" + endDate.getDate()).slice(-2)
    var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
    var year = endDate.getFullYear();

    var someFormattedDate = year+'-'+month+'-'+day;

    $('#price_id').val(price);
    $('#date_id').val(someFormattedDate);
});
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.