I have a sample code:

$("#curday").click(function () { var newdate; date = new Date(); newdate = date.getDate() + '.' + date.getMonth() + '.' + date.getFullYear(); $("#datepicker_down").val(newdate); }); 

But I have problems with him.

  1. The month begins the withdrawal from scratch, that is, I now have the 7th month, and not the 8th, how to fix it?
  2. The date output format is as follows: 07/20/2012, but I want to get this: 07/20/2012, that is, if the number and the month have 1 digit, then the automaton added a zero ahead.

Please help in these nuances. Thank you in advance.

    5 answers 5

    I would advise you not to rack your brains, but to connect the library datejs Then you can write

     $("#datepicker_down").val( (new Date()).toString('dd.MM.yyyy') ); 
    • And this library can do? current day, tomorrow, in a week? to automatically substitute the correct values? - oldzas
    • one
      I will add that over time I use momentjs. And in the case of simple options, self-written functions. - Dmitry Manannikov

    Since I'm lazy, then manually collecting the date is a bummer)) Therefore, we connect this script , then the format method is added to the prototype of the Data class, which performs the date formatting in accordance with the passed template:

     Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); }; 

    And now, mock the date as you like:

     var now = new Date(); now.format("m/dd/yy"); // 8/20/12 now.format("dd.mm.yyyy"); // 20.08.2012 now.format("dd mmm"); // 20 Aug now.format("ddd mmm dd yyyy HH:MM:ss"); // Mon Aug 20 2012 09:06:56 now.format("h:MM:ss TT"); // 9:08:39 AM // и т.д. 

    See an example here.

       var options = { year: 'numeric', month: 'numeric', day: 'numeric', timezone: 'UTC' }; alert(new Date().toLocaleString("ru", options)); // 20.07.2012 

        About ternary operator heard?

         var month = date.getMonth()+1; newdate = date.getDate() + '.' + (month < 10 ? '0' : '') + month + '.' + date.getFullYear(); 

        To work with time there is an excellent library of moment.js .

           /** * Функция добавления к дате date несколько дней указанных в days * @param date * @param days * @return string */ window.dateAdd = function(date, days){ var dateParsed = date.match(/(\d{1,2})-(\d{1,2})-(\d{2,4})/); var date = new Date(dateParsed[3],dateParsed[2],dateParsed[1]); var day = date.getDate()+1; var month = date.getMonth(); var year = date.getFullYear(); if(date<10) date = "0"+date; if(month<10) month = "0"+month; var newdateStr = day + '-' + month + '-' + year; return newdateStr; } 
          • I have corrected the formatting, it is not necessary to insert a snippet, which does nothing at startup, in this case you need to use a block of code - Grundy
          • What does this feature have to do with date formatting? - Pavel Mayorov